Prisma solution to avoid n+1 with findUnique performs mutiple select id from table

169 Views Asked by At

I am using apollo server and nexus with Prisma. I followed this guide to avoid n+1 problem: https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance. This is my User type:

const User = objectType({
    name: 'User',
    definition(t) {
      t.nonNull.id('id');
      t.nonNull.string('name');
      t.list.field('articles', {
        type: nonNull(Article),
        async resolve(parent, _args, ctx) {
          return ctx.prisma.user.findUnique({ where: { id: parent.id } }).articles();
        },
      });
      t.list.field('posts', {
        type: nonNull(Post),
        async resolve(parent, _args, ctx) {
          return ctx.prisma.user.findUnique({ where: { id: parent.id } }).posts();
        },
      });

    },
  });

When invoking the following query:

query usersByName($names: [String]!) {
  users(names: $names) {
    id
    name
    articles {
      id
      name
    }
    posts {
      id
      name
    }
  }
}

Prisma performs the following queries:

[server] prisma:query SELECT "public"."User"."id", "public"."User"."name" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."User"."id" FROM "public"."User" WHERE "public"."User"."id" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."Article"."id", "public"."Article"."userId", "public"."Article"."name" FROM "public"."Article" WHERE "public"."Article"."userId" IN ($1,$2) OFFSET $3
[server] prisma:query SELECT "public"."Post"."id", "public"."Post"."userId", "public"."Post"."name" FROM "public"."Post" WHERE "public"."Post"."userId" IN ($1,$2) OFFSET $3

Why does prisma performs unneeded SELECT "public"."User"."id" FROM "public"."User" queries? How can I avoid that?

0

There are 0 best solutions below