Search code examples
phplaraveleloquentlaravel-query-buildereloquent-relationship

model hasManyThrough relationship using a pivot model


I have the following models/tables:

branch:
    id - integer

department:
    id - integer

teacher:
    id  - integer
    branch_department_id - integer

branch_department:
    id - integer
    branch_id - integer
    department_id - integer
  • each branch has many departments through the pivot table branch_department
  • each branch_department has many teachers

I want to model a hasManythrough relationship between branch and teachers

so from a specific branch i want to get all teachers through every branch_department that is related to that branch

How can I define this?


Solution

  • If you haven't define a BranchDepartment model.

    class BranchDepartment extends Pivot
    {
    }
    

    From here you can just define the hasManyThrough relationship on your Branch model.

    public function teachers()
    {
        return $this->hasManyThrough(
            Teacher::class,
            BranchDepartment::class,
            secondKey: 'branch_department_id',
        );
    }