简体   繁体   中英

relationships with multiple pivot table Eloquent/Laravel

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);
    }

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); });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM