Discover how Prisma relations can save you hours of frustrating database code!
Why Relations in Prisma in NestJS? - Purpose & Use Cases
Imagine building a web app where you have to connect users with their posts, comments, and profiles by writing complex SQL joins manually every time you want to fetch related data.
Manually writing and managing SQL joins is slow, error-prone, and hard to maintain. It's easy to forget a join or write inefficient queries that slow down your app.
Relations in Prisma let you define connections between your data models simply and clearly. Prisma automatically handles the complex queries behind the scenes, so you can fetch related data with easy, readable code.
SELECT * FROM users JOIN posts ON users.id = posts.user_id WHERE users.id = 1;const userWithPosts = await prisma.user.findUnique({ where: { id: 1 }, include: { posts: true } });Relations in Prisma enable you to work with connected data naturally and safely, making your code cleaner and your app faster.
Think of a social media app where you want to show a user's profile along with all their posts and comments without writing complicated SQL every time.
Manually managing data relations is complex and error-prone.
Prisma relations simplify connecting data models with clear code.
This leads to faster development and more reliable apps.
Practice
Solution
Step 1: Understand relation types in Prisma
Prisma supports one-to-one, one-to-many, and many-to-many relations to connect models.Step 2: Identify the relation connecting one record to many
One-to-many means one record in a model relates to multiple records in another model.Final Answer:
One-to-many relation -> Option AQuick Check:
One record linked to many = One-to-many [OK]
- Confusing one-to-one with one-to-many
- Thinking many-to-many is one-to-many
- Assuming no relation means one-to-many
User and Profile models?Solution
Step 1: Check one-to-one relation syntax
One-to-one relations use a single optional foreign key field with @relation specifying fields and references.Step 2: Verify the syntax
The correct schema declaresprofile Profile? @relation(fields: [profileId], references: [id])andprofileId Int?in User, withuser User?in Profile. This matches the pattern for optional one-to-one.Final Answer:
Schema with explicit optional FK and @relation -> Option BQuick Check:
One-to-one uses single foreign key with @relation [OK]
- Using array [] for one-to-one relation
- Missing @relation fields and references
- Not making foreign key optional
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])
}Solution
Step 1: Understand the Prisma query with include
The query fetches a user by id and includes related posts as an array.Step 2: Check relation and data
User with id 1 has two posts, so 'posts' will be an array of two post objects inside the user object.Final Answer:
User object with posts array of two posts -> Option CQuick Check:
Include fetches related data as array [OK]
- Expecting posts to be undefined without include
- Thinking include causes error
- Expecting only posts without user
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])
}Solution
Step 1: Check relation type from schema
Author to Book is one-to-many, so Author.books must be an array of Book.Step 2: Identify the mistake
Author.books is declared as a single Book, which is incorrect for one-to-many.Final Answer:
'books' must be Book[] array -> Option DQuick Check:
One-to-many uses array field [OK]
- Using single object instead of array for many side
- Forgetting @relation decorator
- Making foreign key optional incorrectly
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])
}Solution
Step 1: Understand filtering by related model count
Prisma allows filtering with nested conditions on related models using 'where' and relation filters.Step 2: Identify correct query
UsingfindManyonOrderwithinclude: { customer: true }andwhere: { customer: { orders: { _count: { gt: 5 } } } }fetches the desired orders with customers who have more than 5 orders.Final Answer:
findMany on Order with relational where filter and customer include -> Option AQuick Check:
Filter related model count in where clause [OK]
- Filtering in JavaScript instead of query
- Using incorrect nested where syntax
- Filtering on Customer without including orders count
Ready to prove it?
Pass the test and this pattern moves unknown
