Skip to content

Prisma relations

Prisma relations solve a huge problem with databases and data handling.

Suppose you have a list of users in your app, that create tweets (imagine Twitter).

In your schema you can define the relation between those 2 entities in this way:

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

model User {
  id Int @default(autoincrement()) @id
  tweets Tweet[]
}

When you create a new tweet you associate it with a user with id 1 in this way:

await prisma.tweet.create({
  data: {
    text: req.body.content,
    author: {
      connect: { id: 1 }
    }
  }
})

Then you can retrieve the author information when you get one tweet, with:

await prisma.tweet.findMany({
  include: {
    author: true
  }
})

You can also create a user and populate the database with 2 tweets associated to it:

await prisma.user.create({
  data: {
    tweets: {
      create: [
        { text: 'test' },
        { text: 'test2' },
      ]
    }
  }
})

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list