Eloquent 基于团队的角色

Eloquent team-based roles

我有 3 个 table:角色、团队、用户,每个角色之间有一个支点 table:role_team、role_user、team_user。

我很难利用 Eloquent 来 return 仅用户对特定团队的角色。

$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(),但我想将其指定为关系。我尝试设置 hasManyThrough,但在这种特定情况下它似乎不起作用。

需要将其用作关系而不是查询是因为我正在为 GraphQL 使用 Lighthouse PHP 并且希望能够轻松地查询以下角色:

teams {
  id name 
  users {
    teamPivot {
      roles { id name }
    }
  }
}

任何利用 Eloquent 来实现这一目标的帮助都将不胜感激。

一种可能的解决方案(虽然不一定是我正在寻找的解决方案)是在字段上使用 @method 指令。

设想以下架构:

type User {
  id: ID!
  email: String!
  teams: [Team] @belongsToMany
  teamMeta: TeamUser
}

type Team {
  id: ID!
  name: String!
  users: [User] @belongsToMany
  userMeta: TeamUser
}

type Role {
  id: ID!
  name: String!
  team: Team @belongsTo
  users: [User] @belongsToMany
}

type TeamUser {
  user: User!
  team: Team!
  roles: [Role] @method(name: "getTeamRoles")
}

其中 getTeamRoles 看起来像:

public function getTeamRoles()
{
  return $this->user->roles()->where('team_id', $this->team->id)->get();
}

此配置将允许以下 GraphQL 按需要工作:

  users(first: 1, input: { id: 2 }) {
    email teams {
      name userMeta {
        contactedAt
        roles { id name }
      }
    }
  }

这是目前我运行的解决方案,但最好有一个 "pure" Eloquent 的答案,而不是为每个都编写自定义访问器这种类型的关系。

我认为你可以通过Many to Many关系实现你想要的。

基本上,您需要定义一个方法,该方法 returns belongsToMany 方法在 UserRoles 模型中的结果。

它将是这样的:

User.php

 public function roles(){
     return $this->belongsToMany('App\Role');
 }

Role.php

public function users(){
    return $this->belongsToMany('App\User');
}

然后,您将能够执行如下操作:

$team = Team::find(1);
foreach($team->users as $user) {
    dump($user->roles); 
}

更多参考可以看官方文档:https://laravel.com/docs/6.x/eloquent-relationships#many-to-many

希望对您有所帮助。