skip to Main Content

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?

2

Answers


  1. add branch_department model and:

    class Branch extends Model
    {
        public function teachers()
        {
            return $this->hasManyThrough(
                Teacher::class,
                BranchDepartment::class,
                'branch_id',
                'id',
                'id',
                'teacher_id'
            );
        }
    }
    
    Login or Signup to reply.
  2. 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',
        );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search