Hen*_*Jan 0 pivot-table laravel graphql laravel-lighthouse
在 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
}
Run Code Online (Sandbox Code Playgroud)
并且还假设中间表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');
}
}
Run Code Online (Sandbox Code Playgroud)
为扩展的中间表创建一个类Pivot:
class User_Role extends Pivot
{
public function tag(): BelongsTo
{
return $this->belongsTo(\App\Models\Tag::class, 'tag_id');
}
}
Run Code Online (Sandbox Code Playgroud)
现在更改 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!
}
Run Code Online (Sandbox Code Playgroud)
现在你可以这样查询:
{
users {
id
roles {
id
pivot {
created_at
tag {
id
name
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1065 次 |
| 最近记录: |