【问题标题】:prisma2: how to fetch nested fields?prisma2:如何获取嵌套字段?
【发布时间】:2020-09-14 16:02:45
【问题描述】:

在 prisma 1 中,我使用片段来获取嵌套字段。

例如:

const mutations = {
  async createPost(_, args, ctx) {
    const user = await loginChecker(ctx);
    const post = await prisma.post
      .create({
        data: {
          author: {
            connect: {
              id: user.id,
            },
          },
          title: args.title,
          body: args.body,
          published: args.published,
        },
      })
      .$fragment(fragment);

    return post;
  },
};

但似乎在 prisma2 中不受支持。因为通过在操场上运行它,

mutation CREATEPOST {
  createPost(
    title: "How to sleep?"
    body: "Eat, sleep, repaet"
    published: true
  ) {
    title
    body
    published
    author {
      id
    }
  }
}

我明白了,

"prisma.post.create(...).$fragment is not a function",

【问题讨论】:

    标签: javascript node.js graphql prisma prisma-graphql


    【解决方案1】:

    include option 用于在 Prisma 2 中急切加载关系。

    来自文档的示例:

    const result = await prisma.user.findOne({
      where: { id: 1 },
      include: { posts: true },
    })
    

    假设用户表具有一对多的帖子关系,这也将返回带有帖子字段的用户对象。

    【讨论】:

    • 假设我在 createComment 解析器中包含 {post and author}。从操场上运行时:mutation CREATECOMMENT { createComment(text: "yep, very bad post dude", postId: 4) { id text post { id title author: {id} } author { name } } } 这里我怎样才能获得帖子 {author:id} ?
    • 因此,这与您的架构的定义方式有关,而不是与 prisma 本身有关。假设 createComment 返回一个CommentComment 类型需要将post 作为可查询字段。而Post 类型需要将author 作为可查询字段。
    • 你可以从我的数据模型中看到:gist.github.com/ashiqdev/17d96ac1db30c35ef8e7622992cab035comment 和 post 有关系,post 和 author 有关系。但是,在创建评论时,我包含了 {作者:true,post:true,}。所以,我得到了帖子和作者的直接查询。但是当我尝试发布 {author {id}} 时,我无法得到它。在 prisma1 中,我使用 Fragment 得到了它。
    • prisma 客户端也支持嵌套包括.findOne({ include: { post: { include: { author: true } } } })
    • 带有嵌套包含,我是否也可以添加 where 部分,以便仅获取那些总记录,包括树中特定元素具有特定值的所有层次结构?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2012-04-20
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多