Performance: Relations in Prisma
This affects database query speed and server response time when fetching related data.
const users = await prisma.user.findMany({ include: { posts: true } });const users = await prisma.user.findMany(); for (const user of users) { user.posts = await prisma.post.findMany({ where: { authorId: user.id } }); }
| Pattern | Database Queries | Server Response Time | Client Impact | Verdict |
|---|---|---|---|---|
| N+1 Query Pattern | N+1 queries | High latency | Slow interaction response | [X] Bad |
| Single Query with include | 1 query | Low latency | Fast interaction response | [OK] Good |
User and Profile models?profile Profile? @relation(fields: [profileId], references: [id]) and profileId Int? in User, with user User? in Profile. This matches the pattern for optional one-to-one.prisma.user.findUnique({ where: { id: 1 }, include: { posts: true } }) if user with id 1 has two posts?model User {
id Int @id @default(autoincrement())
name String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
userId Int
user User @relation(fields: [userId], references: [id])
}Author and Book models:model Author {
id Int @id @default(autoincrement())
name String
books Book
}
model Book {
id Int @id @default(autoincrement())
title String
authorId Int
author Author @relation(fields: [authorId], references: [id])
}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])
}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.Pass the test and this pattern moves unknown