如何解决棱镜中的子选择/关系(嵌套列表)

Posted

技术标签:

【中文标题】如何解决棱镜中的子选择/关系(嵌套列表)【英文标题】:How to resolve subselections / relations in prisma (nested lists) 【发布时间】:2019-10-21 04:41:24 【问题描述】:

我们以 prisma 的 github repo 为例:

我们有一个用户,这个用户可以有多个帖子,一个帖子可以有多个链接。

我的目标是检索所有帖子和所有链接。 这意味着,我的回复是列表(帖子)中的列表(链接)。

我想将返回的值映射为两个嵌套列表。

datamodel.prisma

type User 
  id: ID! @id
  email: String! @unique
  name: String
  posts: [Post]!


type Post 
  id: ID! @id
  createdAt: DateTime! @createdAt
  updatedAt: DateTime! @updatedAt
  published: Boolean! @default(value: false)
  title: String!
  content: String
  author: User!
  links: [Link]!


type Link 
  id: ID! @id
  url: String
  title: String
  post: Post!

schema.graphql

type Query 
  ...


type Mutation 
  ...


type Link 
  id: ID!
  url: String
  title: String
  post: Post!


type Post 
  id: ID!
  createdAt: DateTime!
  updatedAt: DateTime!
  published: Boolean!
  title: String!
  content: String
  author: User!


type User 
  id: ID!
  email: String!
  name: String
  posts: [Post]!

我想查询用户的所有帖子,以及响应中每个帖子的所有链接。

如何查询这个请求?

user 
  id
  posts 
    id
    links 
      id
    
  

上面的代码截断器不起作用。

编辑 我想使用以下内容:

User: 
  listPosts: (parent, args, context, info) 
    return context.prisma.posts().links()
  

所以在我的回复中(通过 react-apollo 查询组件在前端的数据),我想映射帖子和每个帖子中的链接。

但是帖子中的链接属性为空。

还有其他方法可以实现吗?!

【问题讨论】:

@DanielRearden Prisma 默认为内联关系,因此在这种情况下,这不是必需的。 你能澄清什么不起作用吗?你看到了什么错误?您实际上是如何在解析器中使用上述查询的? @DanielRearden 更新了我的问题。谢谢。 【参考方案1】:

根据文档:

Prisma 客户端有一个流畅的 API 来查询数据库中的关系。这意味着您可以简单地链接您的方法调用来导航返回记录的关系属性。 只有在检索单个记录时才有可能,而不是列表。这意味着您不能查询列表中返回的记录的关系字段。

为了绕过这个限制,您可以使用$fragment 方法:

const fragment = `
fragment UserWithPostsAndLinks on User 
  id
  email
  name
  posts 
    id
    title
    content
    links 
      id
      url
      title
    
  

`

const userWithPostsAndLinks = await prisma.user( id: args.id ).$fragment(fragment)

【讨论】:

以上是关于如何解决棱镜中的子选择/关系(嵌套列表)的主要内容,如果未能解决你的问题,请参考以下文章

两个棱镜模型之间的一对多和可能对多关系

如何在c ++中删除嵌套列表中的重复元素

从嵌套列表的子数组返回元素的索引

如何在棱镜中搜索 M 到 N 的关系?

有没有办法使用嵌套创建批量更新棱镜中的对象

如何从Rails中的哈希列表中删除嵌套键