Ashik
Ashik

Reputation: 3418

prisma2: how to fetch nested fields?

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",

Upvotes: 13

Views: 19601

Answers (1)

TLadd
TLadd

Reputation: 6884

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

Upvotes: 22

Related Questions