Suppose I have a database schema as follows:
Department -> id | department_name
Employee -> id | department_id | name
Attendance -> id | employee_id | timestamp
I am able to retrieve all attendances from a department using hasManyThrough
relationship as follows from the Department
Model:
public function attendance() {
return $this->hasManyThrough(EmployeeAttendance::class, Employee::class, 'department_id', 'employee_id', 'id', 'id');
}
However, I am trying to do the reverse, i.e retrieve the department of an employee from the attendance model. I have tried to use the hasOneThrough
relationship but I have not been able to get it. I have reviewed the documentation as well as other tutorials on the same. Any help on how I could do so via relationship in the Attendance
model will be appreciated.
CodePudding user response:
You can eager load nested relationships, you can see more about them in the the documentation.
Attendance::with('employee.department')->find($id);
If you are trying to build a relationship between attendance and department you would want to do something like this: In Attendance Model:
public function employee()
{
return $this->belongsToMany(Employee::class);
}
In Employee Model:
public function department()
{
return $this->belongsToMany(Department::class);
}