Laravel Lighthouse GraphQL 从连接三个 table 的枢轴 table 查询数据

Laravel Lighthouse GraphQL query data from a pivot table that connects three tables

在 Laravel Lighthouse GraphQL 中,如何从中间 "pivot" table 检索信息?

假设我在 belongsToMany 关系中有用户和角色:

type User {
  roles: [Role!]! @belongsToMany
}

type Role {
  users: [User!]! @belongsToMany
}

type Query {
    user(id: ID! @eq): User @find
    role(id: ID! @eq): Role @find
}

并且假设中间 table User_Role 包含列 "created_at" 和 "tag_id"。
我将如何在我的查询中包含 "created_at"?
我如何获得 tag_id 所指的标签?

我发现你可以这样做:

首先,确保 User 模型中的关系调用 ->withPivot('created_at', 'tag_id'):

class User extends Model {
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(\App\Models\Role::class, 'User_Role')
                    ->using(User_Role::class) // only needed to retrieve the tag from the tag_id
                    ->withPivot('created_at', 'tag_id');
    } 
}

为扩展 Pivot:

的中间体 table 创建一个 class
class User_Role extends Pivot
{
    public function tag(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Tag::class, 'tag_id');
    }
}

现在修改GraphQL代码如下:

type User {
    id: ID!
    roles: [Role!] @belongsToMany
}

type Role {
    id: ID!
    pivot: UserRolePivot # this is where the magic happens
}

type UserRolePivot {
    created_at: Date!
    tag: Tag! @belongsTo
}

type Tag {
    id: ID!
    name: String!
}

现在您可以这样查询:

{
  users {
    id
    roles {
      id
      pivot {
        created_at
        tag {
          id
          name
        }
      }
    }
  }
}