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.