0
votes

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']
        );
    }
}
1
Does User::with('teams.roles') work?DigitalDrifter
I tried that and got the same RelationNotFoundExceptionRaphael Bruno

1 Answers

1
votes

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