Node.js, Prisma & PostgreSQL

Lesson 7 of 12

Modeling Relations: One-to-Many and Many-to-Many

Just like the JOINs you wrote in SQL, Prisma models real relationships between tables, but you declare them once in the schema.

One-to-many

One User can have many Posts:

model User {
  id    Int    @id @default(autoincrement())
  email String @unique
  posts Post[]
}

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

authorId is a real foreign-key column, author/posts are the Prisma-side relation fields you query through.

Many-to-many

A Post can have many Tags, and a Tag can apply to many Posts:

model Post {
  id    Int   @id @default(autoincrement())
  title String
  tags  Tag[]
}

model Tag {
  id    Int    @id @default(autoincrement())
  name  String @unique
  posts Post[]
}

Prisma automatically creates and manages the hidden join table behind the scenes, the same _PostToTag style table you'd have written by hand in SQL.

📝 Relations Quiz

Passing score: 70%
  1. 1.In a one-to-many relation, which side holds the actual foreign-key column?

  2. 2.A many-to-many relation like Post.tags and Tag.posts is backed by a hidden ____ table.

  3. 3.For an implicit many-to-many relation, you must manually create the join table yourself.