0
0
NestJSframework~30 mins

Relations in Prisma in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Relations in Prisma with NestJS
📖 Scenario: You are building a simple blog backend using NestJS and Prisma. You want to model authors and their posts. Each author can have many posts, and each post belongs to one author.
🎯 Goal: Create Prisma models for Author and Post with a one-to-many relation. Then, write NestJS Prisma service code to fetch all posts with their authors.
📋 What You'll Learn
Create Prisma models Author and Post with a one-to-many relation
Add a config variable for Prisma client instance
Write a NestJS service method to fetch all posts including their author data
Complete the NestJS service class with Prisma client injection
💡 Why This Matters
🌍 Real World
Modeling and querying related data like users and their posts is common in web applications such as blogs, social media, and content management systems.
💼 Career
Understanding Prisma relations and integrating Prisma with NestJS is valuable for backend developers building scalable and maintainable APIs.
Progress0 / 4 steps
1
Define Prisma models for Author and Post
In your schema.prisma file, create two models: Author and Post. Define Author with fields id (Int, auto-increment, primary key) and name (String). Define Post with fields id (Int, auto-increment, primary key), title (String), and authorId (Int). Set up a one-to-many relation where Author has many posts and Post belongs to one author.
NestJS
Need a hint?

Remember to use @relation attribute on the Post model to link to Author.

2
Create Prisma client instance in NestJS service
In your NestJS service file, import PrismaClient from @prisma/client and create a constant called prisma that is a new instance of PrismaClient.
NestJS
Need a hint?

Use new PrismaClient() to create the client instance.

3
Write a method to fetch all posts with their authors
Inside your NestJS service class, write an async method called getAllPosts that returns all posts including their related author data. Use prisma.post.findMany with the include option to include author.
NestJS
Need a hint?

Use include: { author: true } inside findMany to get author data.

4
Inject Prisma client into NestJS service class
Modify the PostService class to inject PrismaClient via the constructor. Add a private readonly property called prisma of type PrismaClient and assign it in the constructor parameter. Update the getAllPosts method to use this.prisma instead of the global prisma variable.
NestJS
Need a hint?

Use constructor injection to get PrismaClient instance and use this.prisma inside methods.