0

在 Laravel Lighthouse GraphQL 中,如何从中间“数据透视”表中检索信息?

假设我在 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
}

并且还假设中间表User_Role包含列“created_at”和“tag_id”。
我将如何在我的查询中包含“created_at”?
我将如何获得tag_id引用的标签?

4

1 回答 1

7

我发现你可以这样做:

首先,确保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

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
        }
      }
    }
  }
}
于 2020-01-12T16:53:32.333 回答