Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajsmith_codes's avatar

Multiple pivots related to one model?

I have a situation I can't seem to figure out the logic for. I have a Users table and each User can be assigned a role (in a separate table). Each User also belongs to a Department.

Some users have the role of Supervisor, and they are supervisors of other users. I figure it's better to assign a Supervisor to a Department instead of each user. So, I created two pivot tables:

1st pivot table called user_departments user_id department_id

2nd pivot table called supervisor_departments user_id department_id

If I call $user->departments, I get the values from the 1st pivot table and that is correct.

If I call $supervisor->departments, I get the same values from the 1st pivot, when I should be getting values from the 2nd pivot.

Here are the models:

Department model

public function users()
{

    return $this->belongsToMany('App\User', 'user_departments',  'department_id', 'user_id');

}

public function supervisors(){

    $this->belongsTo('App\Supervisor','department_id', 'user_id');

}

User Model

public function departments()
{
    return $this->belongsToMany('App\Department', 'user_departments','user_id', 'department_id');
}

Supervisor Model

public function departments(){

    $this->hasMany('App\Departments')->withPivot('supervisor_departments');

}

Hopefully, someone can pinpoint what I'm missing or doing wrong. Thanks in advance!

0 likes
10 replies
bugsysha's avatar

Supervisor is still a user. You are doing the same thing with just different variable names.

For your design, you need another many to many relationship inside the user model which uses the supervisor_departments table.

ajsmith_codes's avatar

I tried that at first with no luck. However, it may have been that I didn't get it correct. Is this close?

public function supervisors(){

    $this->belongsTo('App\Supervisor', 'supervisor_departments','user_id', 'department_id');

}
bugsysha's avatar

Wait I've missed Supervisor model. Let me take another look.

bugsysha's avatar

Your database is using Many To Many pattern, while your relationships are Has Many pattern.

You do not need supervisor_departments, but you need supervisor_id on departments table.

ajsmith_codes's avatar

I was hoping to avoid assigning a supervisor to each person. I wanted to assign a supervisor to a department or departments instead. Is that possible?

bugsysha's avatar

Did you read what I've wrote? I didn't mention person at all. What do you want with a person? And is a person represented by User model?

bugsysha's avatar
bugsysha
Best Answer
Level 61

To me it seems like you are only being confused by the Supervisor model. Remove it and add role column to User model.

Please or to participate in this conversation.