我有这个关系并为所有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);
}
但是它不工作。有人能告诉我如何过滤查询结果与关系?
您可以在其中查询与关系,如
$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
类似于