Skip to content

Prisma relations

New Course Coming Soon:

Get Really Good at Git

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' },
      ]
    }
  }
})
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my SQL Tutorial on The Valley of Code

Here is how can I help you: