Reputation: 66
I'm searching to load a relation inside a pivot table with "->with()".
Table structure: Are 5 tables and Laravel Eloquent models
user (id)
team (id)
role (id)
team_user (id, team_id, user_id)
team_user_role (id, team_user_id, role_id)
class User extends Model {
function teams(){
return $this->belongsToMany(Team::class)
->using(TeamUser::class);
}
}
class Team extends Model {
function users(){
return $this->belongsToMany(User::class)
->using(TeamUser::class);
}
}
class TeamUser extends Pivot {
function roles(){
return $this->belongsToMany(Role::class)
->using(TeamUserRole::class);
}
}
class Role extends Model {}
class TeamUserRole extends Pivot {}
Ok, I can do that and this works perfectly, the "->with()" function load roles relationship from TeamUser...
TeamUser::with('roles')->first()->roles // return list of Role::class
...but I need load this "roles" relationship from User::class "User->teams->roles":
User::with('teams')
->with('teams.pivot.roles') // Something like this
->first()->teams->pivot->roles; // Expected a list of Role::class
This way a got a RelationNotFoundException, that's make sense because 'pivot' is not a relationship...
So, in this scenery, how can I access the list of roles from user using QueryBuilder?
Thanks.
[Edit]
I tried:
User::with('teams.roles') // got a RelationNotFoundException
Upvotes: 0
Views: 4275
Reputation: 4412
You have to use the withPivot()
method in your model :
class Role extends Model {
public function
}
then :
User::with('teams')
->with('teams.roles') // Something like this
->first()->teams->pivot->{attributes};
If you really want to access the Role pivot as an eloquent model :
class User extends Model {
function teams(){
return $this->belongsToMany(Team::class)
->using(TeamUser::class);
}
function roles(){
return $this->hasManyThrough(Role::class, Team::class);
}
}
User::with('roles')->get();
see the docs for more informations :
https://laravel.com/docs/8.x/eloquent-relationships#has-many-through
If you need a more deep relation in your case, you should considerate this package :
https://github.com/staudenmeir/eloquent-has-many-deep
Upvotes: 1