Hi dear prisma team :wave: I have a question to th...
# orm-help
o
Hi dear prisma team 👋 I have a question to the way prisma handles the relation query Giving the following schema:
Copy code
model User {
  id       Int       @id @default(autoincrement())
  username String?   @unique
  contexts Context[]
}

model Context {
  id          Int         @id @default(autoincrement())
  contextName String
  user        User        @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId      Int
}
I want to get all of the contexts belonging to the user. If I write in the way prisma suggest me to write:
Copy code
const userContextsSample = await this.prisma.user.findUnique({
      where: {
        id: userId,
      },
      include: {
        contexts: true,
      },
    });
I see that prisma generates two SQL queries:
Copy code
prisma:query SELECT "public"."User"."id", "public"."User"."username" FROM "public"."User" WHERE "public"."User"."id" = $1 LIMIT $2 OFFSET $3

prisma:query SELECT "public"."Context"."id", "public"."Context"."contextName", "public"."Context"."userId", "public"."Context"."createdAt" FROM "public"."Context" WHERE "public"."Context"."userId" IN ($1) OFFSET $2
This looks quite suboptimal to me. As I have already the
userId
in place I would expect just one single SQL query:
Copy code
SELECT "public"."Context"."id", "public"."Context"."contextName", "public"."Context"."userId", "public"."Context"."createdAt" FROM "public"."Context" WHERE "public"."Context"."userId" IN ($myOriginalUserId)
Is there a way prisma can achieve that? Many thanks in advance!
r
@Oleg Yarin 👋 In this case, you are querying for both the user and context so Prisma will generate 2 queries. If you only want the contexts, use the following:
Copy code
await prisma.context.findMany({
  where: { userId }
})
💚 1
o
@Ryan Thank you! This was easy 😄
🙌 1