0
0
NestJSframework~5 mins

Relations in Prisma in NestJS

Choose your learning style9 modes available
Introduction

Relations in Prisma help you connect different data tables easily. They let you link related information so you can get all connected data in one go.

When you want to link users with their posts in a blog app.
When you need to connect orders with customers in a shop system.
When you want to fetch comments related to a specific article.
When you want to organize data that belongs together, like products and categories.
Syntax
NestJS
model User {
  id    Int     @id @default(autoincrement())
  name  String
  posts Post[]  // One user has many posts
}

model Post {
  id       Int    @id @default(autoincrement())
  title    String
  content  String
  authorId Int
  author   User   @relation(fields: [authorId], references: [id])
}

Use arrays (e.g., Post[]) to show one-to-many relations.

The @relation attribute links fields between models.

Examples
Basic one-to-many relation: one user has many posts.
NestJS
model User {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}

model Post {
  id       Int    @id @default(autoincrement())
  title    String
  authorId Int
  author   User   @relation(fields: [authorId], references: [id])
}
One category has many products linked by categoryId.
NestJS
model Category {
  id       Int      @id @default(autoincrement())
  name     String
  products Product[]
}

model Product {
  id          Int      @id @default(autoincrement())
  name        String
  categoryId  Int
  category    Category @relation(fields: [categoryId], references: [id])
}
One-to-one relation: a user has one profile.
NestJS
model Profile {
  id     Int  @id @default(autoincrement())
  bio    String
  userId Int  @unique
  user   User @relation(fields: [userId], references: [id])
}

model User {
  id      Int      @id @default(autoincrement())
  name    String
  profile Profile?
}
Sample Program

This code creates a user named Alice with two posts. It then prints the user name and all her posts.

NestJS
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  // Create a user
  const user = await prisma.user.create({
    data: {
      name: 'Alice',
      posts: {
        create: [
          { title: 'Hello World', content: 'My first post' },
          { title: 'Prisma is cool', content: 'Learning relations' }
        ]
      }
    },
    include: { posts: true }
  });

  console.log(`User: ${user.name}`);
  console.log('Posts:');
  user.posts.forEach(post => {
    console.log(`- ${post.title}: ${post.content}`);
  });
}

main()
  .catch(e => console.error(e))
  .finally(async () => {
    await prisma.$disconnect();
  });
OutputSuccess
Important Notes

Always define the foreign key field (like authorId) when using relations.

Use include in queries to fetch related data together.

Remember to disconnect Prisma client to avoid hanging connections.

Summary

Relations connect different models to organize related data.

Use arrays for one-to-many and single fields for one-to-one relations.

Prisma makes fetching connected data simple with include.