Skip to contentPedro Farbo
Lesson 11 / 2550 min

Database Relationships

Database Relationships

Learn to model relationships between tables with Prisma.

Types of Relationships

One-to-Many

Category → Products (one category has many products)

prisma
model Category {  id       String    @id @default(uuid())  name     String  products Product[]} model Product {  id         String   @id @default(uuid())  name       String  category   Category @relation(fields: [categoryId], references: [id])  categoryId String}

Many-to-Many

Products ↔ Orders

prisma
model Order {  id    String      @id @default(uuid())  items OrderItem[]} model Product {  id    String      @id @default(uuid())  items OrderItem[]} model OrderItem {  id        String  @id @default(uuid())  order     Order   @relation(fields: [orderId], references: [id])  orderId   String  product   Product @relation(fields: [productId], references: [id])  productId String  quantity  Int   @@unique([orderId, productId])}

Queries with Relationships

typescript
// Include relationsconst order = await prisma.order.findUnique({  where: { id: orderId },  include: {    items: {      include: { product: true }    }  }}); // Nested createconst order = await prisma.order.create({  data: {    userId: user.id,    items: {      create: [        { productId: 'abc', quantity: 2 },        { productId: 'def', quantity: 1 }      ]    }  }}); // Filter by relationconst products = await prisma.product.findMany({  where: {    category: { slug: 'electronics' }  }});

Cascade Operations

prisma
model Cart {  id    String     @id @default(uuid())  items CartItem[]} model CartItem {  id     String @id @default(uuid())  cart   Cart   @relation(fields: [cartId], references: [id], onDelete: Cascade)  cartId String}

When cart is deleted, all items are deleted too.

Summary

  • ✅ One-to-Many relationships
  • ✅ Many-to-Many with junction table
  • ✅ Nested queries
  • ✅ Cascade operations

Next lesson: JWT Authentication! 🚀

Enjoyed the content? Your contribution helps keep everything online and free!

PIX:0737160d-e98f-4a65-8392-5dba70e7ff3e