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 solved this situation with answer of @Mathieu Ferre
Using this dependency
https://github.com/staudenmeir/eloquent-has-many-deep
class User extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
...
function roles(){
return $this->hasManyDeep(Roles::class,
[TeamUser::class, TeamUserRole::class],
['user_id', 'team_user_id', 'id'],
['id', 'id', 'role_id']
);
}
}
User::with('teams.roles')
work? – DigitalDrifter