Bird
Raised Fist0
NestJSframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What type of relation in Prisma connects one record to many records in another model?
easy
A. One-to-many relation
B. One-to-one relation
C. Many-to-many relation
D. No relation

Solution

  1. Step 1: Understand relation types in Prisma

    Prisma supports one-to-one, one-to-many, and many-to-many relations to connect models.
  2. 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.
  3. Final Answer:

    One-to-many relation -> Option A
  4. Quick Check:

    One record linked to many = One-to-many [OK]
Hint: One record to many records means one-to-many relation [OK]
Common Mistakes:
  • Confusing one-to-one with one-to-many
  • Thinking many-to-many is one-to-many
  • Assuming no relation means one-to-many
2. Which of the following is the correct Prisma schema syntax for a one-to-one relation between User and Profile models?
easy
A. model User {\n id Int @id @default(autoincrement())\n profiles Profile[]\n}\n\nmodel Profile {\n id Int @id @default(autoincrement())\n user User\n}
B. model User {\n id Int @id @default(autoincrement())\n profile Profile? @relation(fields: [profileId], references: [id])\n profileId Int?\n}\n\nmodel Profile {\n id Int @id @default(autoincrement())\n user User?\n}
C. model User {\n id Int @id @default(autoincrement())\n profile Profile\n}\n\nmodel Profile {\n id Int @id @default(autoincrement())\n user User\n}
D. model User {\n id Int @id @default(autoincrement())\n profileId Int\n}\n\nmodel Profile {\n id Int @id @default(autoincrement())\n}

Solution

  1. 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.
  2. Step 2: Verify the syntax

    The correct schema declares 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.
  3. Final Answer:

    Schema with explicit optional FK and @relation -> Option B
  4. Quick Check:

    One-to-one uses single foreign key with @relation [OK]
Hint: One-to-one needs single foreign key with @relation fields [OK]
Common Mistakes:
  • Using array [] for one-to-one relation
  • Missing @relation fields and references
  • Not making foreign key optional
3. Given the Prisma models below, what will be the result of the query 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])
}
medium
A. An error because 'include' is not valid here
B. An object with user data but 'posts' will be undefined
C. An object with user data and an array of two post objects under 'posts'
D. An array of posts only without user data

Solution

  1. Step 1: Understand the Prisma query with include

    The query fetches a user by id and includes related posts as an array.
  2. 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.
  3. Final Answer:

    User object with posts array of two posts -> Option C
  4. Quick Check:

    Include fetches related data as array [OK]
Hint: Include fetches related records as array or object [OK]
Common Mistakes:
  • Expecting posts to be undefined without include
  • Thinking include causes error
  • Expecting only posts without user
4. Identify the error in this Prisma schema for a one-to-many relation between 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])
}
medium
A. Author model is missing a primary key
B. Missing @relation on Author.books field
C. authorId should be optional in Book model
D. The 'books' field in Author should be an array (Book[]) not a single Book

Solution

  1. Step 1: Check relation type from schema

    Author to Book is one-to-many, so Author.books must be an array of Book.
  2. Step 2: Identify the mistake

    Author.books is declared as a single Book, which is incorrect for one-to-many.
  3. Final Answer:

    'books' must be Book[] array -> Option D
  4. Quick Check:

    One-to-many uses array field [OK]
Hint: One-to-many needs array [] on 'many' side field [OK]
Common Mistakes:
  • Using single object instead of array for many side
  • Forgetting @relation decorator
  • Making foreign key optional incorrectly
5. 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])
}
hard
A. Use findMany on Order with include: { customer: true } and a where on customer orders count > 5
B. Use findMany on Customer with where: { orders: { some: {} } } and include orders
C. Use findMany on Order with where: { customer: { orders: { count: { gt: 5 } } } } and include customer
D. Use findMany on Customer with include: { orders: true } and filter orders count > 5 in JavaScript

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]
Hint: 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard