我有 3 个表:角色、团队、用户,每个表之间都有一个数据透视表:role_team、role_user、team_user。
我很难利用 Eloquent 仅返回用户在特定团队中拥有的角色。
$team = Team::find(1);
foreach($team->users as $user) {
dump($user->teamRoles); // Get the roles this user has for the team
}
虽然可以$user->roles()->where('team_id', $team->id)->get()
,但我想将其指定为关系。我尝试设置 a hasManyThrough
,但在这种特定情况下似乎不起作用。
需要将其用作关系而不是查询是因为我将 Lighthouse PHP 用于 GraphQL,并且希望能够轻松地查询以下角色:
teams {
id name
users {
teamPivot {
roles { id name }
}
}
}
任何利用 Eloquent 来实现这一点的帮助将不胜感激。