0
0
NestJSframework~10 mins

Relations in Prisma in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Relations in Prisma
Define Models
Add Relation Fields
Generate Prisma Client
Use Client to Query
Access Related Data
Update or Create with Relations
This flow shows how to define related models in Prisma, generate the client, and then query or update related data.
Execution Sample
NestJS
model User {
  id    Int     @id @default(autoincrement())
  posts Post[]
}

model Post {
  id     Int  @id @default(autoincrement())
  userId Int
  user   User @relation(fields: [userId], references: [id])
}
Defines User and Post models with a one-to-many relation: a User has many Posts, each Post belongs to one User.
Execution Table
StepActionModel StatePrisma Client QueryResult
1Define User model with posts fieldUser has posts: Post[]N/AModels ready
2Define Post model with userId and user relationPost has userId and user relationN/AModels ready
3Run prisma generateClient generated with relationsN/AClient ready
4Create User with no postsUser created with id=1prisma.user.create({ data: {} })User id=1 created
5Create Post linked to User id=1Post created with userId=1prisma.post.create({ data: { userId: 1 } })Post linked to User 1
6Query User with posts includedUser with posts loadedprisma.user.findUnique({ where: { id: 1 }, include: { posts: true } })User with posts array returned
7Query Post with user includedPost with user loadedprisma.post.findUnique({ where: { id: 1 }, include: { user: true } })Post with user object returned
8ExitN/AN/AEnd of example
💡 All steps completed to show relation definition, creation, and querying in Prisma.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 6After Step 7Final
Userundefined{ id: 1, posts: [] }{ id: 1, posts: [] }{ id: 1, posts: [{ id: 1, userId: 1 }] }{ id: 1, posts: [{ id: 1, userId: 1 }] }{ id: 1, posts: [{ id: 1, userId: 1 }] }
Postundefinedundefined{ id: 1, userId: 1 }{ id: 1, userId: 1 }{ id: 1, userId: 1, user: { id: 1 } }{ id: 1, userId: 1, user: { id: 1 } }
Key Moments - 3 Insights
Why do we need both userId and user fields in the Post model?
The userId stores the foreign key, while the user field defines the relation and allows Prisma to fetch the related User object. See execution_table steps 2 and 5.
How does Prisma know which fields link the models?
The @relation attribute specifies which fields connect models, like fields: [userId] and references: [id] in Post. See execution_table step 2.
What happens when we include related data in queries?
Prisma fetches the related records and adds them to the result, like posts inside User or user inside Post. See execution_table steps 6 and 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5. What is the value of Post.userId after creation?
Aundefined
B1
Cnull
D0
💡 Hint
Check the 'Model State' column at step 5 in execution_table.
At which step does the User object include its posts array?
AStep 6
BStep 5
CStep 4
DStep 7
💡 Hint
Look for 'User with posts loaded' in the 'Result' column.
If we remove the @relation attribute from Post.user, what changes in the execution?
AUser.posts will still work normally
BPost.userId will be removed
CPrisma will not link Post to User automatically
DNo change in queries
💡 Hint
Refer to key_moments about the role of @relation attribute.
Concept Snapshot
Prisma relations connect models via fields and @relation.
Use foreign keys (e.g., userId) and relation fields (e.g., user).
Generate Prisma Client to query related data.
Include related records with include: { relationName: true }.
Relations enable easy nested queries and data integrity.
Full Transcript
Relations in Prisma let you connect two models, like User and Post, so you can easily fetch related data. You define models with fields that link them, such as a userId in Post and a posts array in User. The @relation attribute tells Prisma how these fields connect. After defining models, you run prisma generate to create the client. Then you can create records linked by relations and query them including related data. For example, fetching a User with all their Posts or a Post with its User. This visual trace showed each step from model definition, client generation, creating records, to querying with relations included. Understanding how foreign keys and relation fields work together is key to using Prisma relations effectively.