relationships with multiple pivot table Eloquent/Laravel

Viewed 88

I have 4 table

users
 id
 name

school
 id
 name

user_school
 id
 user_id
 school_id

user_role
 id
 user_role
 role_id

We need to find school users list whose have role id is 2

we use belongsToMany but not success

public function totalAdmin(){
        return $this->belongsToMany('App\Models\User','user_school', 'school_id','user_id')->where('user_school.status',1)->where('user_school.deleted',0);
    }
1 Answers

Assuming you have relationships:

  • User-Role named roles (with pivot user_role)
  • School-User named users (with pivot user_school)

You can do:

School::users()->whereHas('roles', function ($q) {
   $q->where('id', 2);
});

You can probably transfer it in the relationship as well:

public function totalAdmin(){
    return $this->belongsToMany('App\Models\User','user_school','school_id','user_id')
      ->whereHas('roles', function($q) { $q->where('id', 2); });
}
Related