我正在搜索在数据透视表中加载带有“”的关系-
表结构: 5表和Laravel雄辩模型
用户(id)
团队(id)
角色(id)
团队用户(id,团队id,用户id)
团队用户角色(id,团队用户id,角色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 {}
好吧,我能做到,而且效果很好,“-
TeamUser::with('roles')->first()->roles // return list of Role::class
...但是我需要从User::class“User”加载这个“角色”关系-
User::with('teams')
->with('teams.pivot.roles') // Something like this
->first()->teams->pivot->roles; // Expected a list of Role::class
这样就有了关系基础例外,这是有意义的,因为“支点”不是关系...
那么,在这个场景中,如何使用QueryBuilder从用户访问角色列表?
谢谢
我用@Mathieu Ferre的回答解决了这个问题
使用此依赖项
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']
);
}
}
您必须在模型中使用withPivot()
方法:
class Role extends Model {
public function
}
然后:
User::with('teams')
->with('teams.roles') // Something like this
->first()->teams->pivot->{attributes};
如果您确实希望以雄辩的模型访问角色轴:
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();
有关更多信息,请参阅文档:
https://laravel.com/docs/8.x/eloquent-relationships#has-许多通过
如果你需要一个更深入的关系在你的情况下,你应该考虑这个包:
https://github.com/staudenmeir/eloquent-has-many-deep