【问题标题】:Laravel Lighthouse GraphQL query data from a pivot table that connects three tablesLaravel Lighthouse GraphQL 从连接三个表的数据透视表查询数据
【发布时间】:2020-01-13 00:53:32
【问题描述】:

在 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 所指的标签?

【问题讨论】:

    标签: laravel graphql pivot-table laravel-lighthouse


    【解决方案1】:

    我发现你可以这样做:

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

    【讨论】:

    • 谢谢!文档/github问题中有吗?有什么方法可以更改属性的名称,我想使用“product_pivot”而不是“pivot”,这太通用了
    • 很久以前我不知道我是如何找到答案的,也不知道去哪里找。我想如果你把我的代码改成type Role {id: ID! product_pivot: UserRolePivot},你就会得到你想要的。
    • @HendrikJan 这不起作用,单数或复数(即products_pivot
    猜你喜欢
    • 2021-02-22
    • 2021-01-22
    • 1970-01-01
    • 2020-01-23
    • 2018-11-11
    • 2015-06-24
    • 1970-01-01
    • 2020-08-09
    相关资源
    最近更新 更多