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



让我们举一个来自Prisma的github存储库的例子:

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

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

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

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 查询组件在前端的数据(,我想映射帖子和每个帖子中的链接。

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

有没有其他方法可以实现这一目标?!

根据文档:

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)

最新更新