Laravel模型中如何用hasOneThrough关联实现Attendance反查所属部门
正确实现方案
方案1:使用hasOneThrough直接关联(一步拿到部门)
在Attendance模型中按如下参数定义关联即可,hasOneThrough反向关联的参数顺序容易和正向的hasManyThrough搞混,按下方对应关系配置即可:
public function department() { return $this->hasOneThrough( Department::class, // 最终要获取的目标模型 Employee::class, // 中间关联模型 'id', // 中间表(employees表)和当前表(attendances表)关联的字段:employees.id 'id', // 目标表(departments表)和中间表关联的字段:departments.id 'employee_id', // 当前表(attendances表)关联中间表的外键:attendances.employee_id 'department_id' // 中间表(employees表)关联目标表的外键:employees.department_id ); }
定义完成后可以直接通过$attendance->department获取对应考勤记录的所属部门。
方案2:嵌套关联(可读性更高、更常用)
如果你的项目中本身就需要考勤关联员工、员工关联部门的基础关联,不需要额外记忆hasOneThrough的参数顺序,用嵌套关联更易维护:
- 先在
Attendance模型中定义到员工的关联:
public function employee() { return $this->belongsTo(Employee::class, 'employee_id'); }
- 再在
Employee模型中定义到部门的关联(如果已经定义过可以跳过):
public function department() { return $this->belongsTo(Department::class, 'department_id'); }
使用时通过链式调用即可获取部门:$attendance->employee->department,预加载时使用Attendance::with('employee.department')->get()即可避免N+1查询问题,性能和hasOneThrough方案一致。
内容的提问来源于stack exchange,提问作者jptl431
相关产品推荐
相关产品推荐

