Bird
0
0

Which Prisma query approach correctly applies this filter using relations?

hard📝 Application Q15 of 15
NestJS - Database with Prisma
You want to fetch all Order records with their related Customer data, but only include customers who have placed more than 5 orders. Which Prisma query approach correctly applies this filter using relations?

model Customer {
  id     Int     @id @default(autoincrement())
  name   String
  orders Order[]
}

model Order {
  id         Int      @id @default(autoincrement())
  total      Float
  customerId Int
  customer   Customer @relation(fields: [customerId], references: [id])
}
AUse <code>findMany</code> on Order with <code>include: { customer: true }</code> and a <code>where</code> on customer orders count > 5
BUse <code>findMany</code> on Customer with <code>where: { orders: { some: {} } }</code> and include orders
CUse <code>findMany</code> on Order with <code>where: { customer: { orders: { count: { gt: 5 } } } }</code> and include customer
DUse <code>findMany</code> on Customer with <code>include: { orders: true }</code> and filter orders count > 5 in JavaScript
Step-by-Step Solution
Solution:
  1. Step 1: Understand filtering by related model count

    Prisma allows filtering with nested conditions on related models using 'where' and relation filters.
  2. Step 2: Identify correct query

    Using findMany on Order with include: { customer: true } and where: { customer: { orders: { _count: { gt: 5 } } } } fetches the desired orders with customers who have more than 5 orders.
  3. Final Answer:

    findMany on Order with relational where filter and customer include -> Option A
  4. Quick Check:

    Filter related model count in where clause [OK]
Quick Trick: Filter related model count in where clause with include [OK]
Common Mistakes:
  • Filtering in JavaScript instead of query
  • Using incorrect nested where syntax
  • Filtering on Customer without including orders count

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes