9

In prisma 1 I have used fragment to fetch the nested fields.

For example:

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;
  },
};

but seems like in prisma2 it is not supported. because by running this on playground,

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

I am getting,

"prisma.post.create(...).$fragment is not a function",
Ashik
  • 2,888
  • 8
  • 28
  • 53

1 Answers1

17

The include option is used to eagerly load relations in Prisma.

Example from docs:

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

Assuming a user table with a one-to-many posts relation, this will return back the user object with the posts field as well.

Prisma also supports nesting as well, for example:

const result = await prisma.user.findOne({
  where: { id: 1 },
  include: {
    posts: {
      include: {
        author: true,
      }
    },
  },
})
matth
  • 6,112
  • 4
  • 37
  • 43
TLadd
  • 6,488
  • 2
  • 32
  • 40
  • suppose I include {post and author} in createComment resolver. when running this from playground: ```mutation CREATECOMMENT { createComment(text: "yep, very bad post dude", postId: 4) { id text post { id title author: {id} } author { name } } } ``` here how can I get posts {author:id} ? – Ashik May 28 '20 at 12:45
  • So that has more to do with how your schema is defined than prisma itself. Assuming createComment returns a `Comment`, the `Comment` type needs to have `post` as a queryable field. And the `Post` type needs to have `author` as a queryable field. – TLadd May 28 '20 at 13:56
  • you can see from my data model: https://gist.github.com/ashiqdev/17d96ac1db30c35ef8e7622992cab035 comment has relation with post and post has relation with author. but, when created a comment I included { author: true, post: true,}. so, I got post and authors direct queries. but when I try to get post {author {id}} I can't get it. In prisma1 by using fragment I used to got it. – Ashik May 28 '20 at 14:05
  • 10
    The prisma client supports nesting includes as well `.findOne({ include: { post: { include: { author: true } } } })` – TLadd May 28 '20 at 14:34
  • with nested includes, can i also add where parts so to only get those total records including all the hierarchy where a specific element deep in the tree has a specific value? – Sebastian Stuecker Dec 19 '20 at 08:50