【问题标题】:Laravel filtering query results with relationsLaravel 使用关系过滤查询结果
【发布时间】:2021-11-15 04:58:37
【问题描述】:

I have this relations 并为所有 3 个表定义了模型

class Employee extends Model
{
    use HasFactory;
    protected $table = 'employees';
    public function departments()
    {
        return $this->belongsToMany(Department::class, 'dept_emp', 'emp_no', 'dept_no', 'emp_no', 'dept_no');
    }
}
class Department extends Model
{
    use HasFactory;
    protected $table = 'departments';

}
class Dept_emp extends Model
{
    use HasFactory;
    protected $table = 'dept_emp';
}

在我的控制器中

 $employees = Employee::with('departments')->paginate(50);

我想过滤这个查询结果,以便能够只选择一个选定的部门,而不是全部。

我尝试将此功能添加到员工模型中

    public function scopeDepartment($query, $department)
    {
        return $query->where('dept_no',$department);
    }

但它不起作用。有人可以建议我如何使用关系过滤查询结果吗?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你可以像这样在关系中查询

    $employees = Employee::with(['departments' => function($q) use ($dept_id){
      $q->where('dept_no',$dept_id);
    }])->paginate(50);
    

    $dept_id 是部门的 ID,即 $dept_id = $request->department_id 类似

    【讨论】:

    • 在我使用 ``` $employees =Employee::with(['departments' => function($q) 使用 ($dept){$q->where('dept_no',$部门);}])->分页(50); ``` 我收到错误 SQLSTATE [23000]:完整性约束违规:1052 where 子句中的列 'dept_no' 不明确
    • 在我将 'dept_no' 更改为 'departments.dept_no' 后,查询有效,但对于每行项目,此关系为空 []
    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多