Establishing Model Relations in Prisma
Relational databases structure data using foreign key references. Prisma models support three types of database relationships: One-to-One, One-to-Many, and Many-to-Many.
1. One-to-Many Relationships (User and Posts)
A one-to-many relationship is the most common association. For example, a User can author multiple posts, but each Post belongs to a single author.
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
authorId Int
author User @relation(fields: [authorId], references: [id])
}posts Post[]declares the list connection.@relation(fields: [authorId], references: [id])binds the localauthorIdforeign key to the primary keyidof the User model.
2. One-to-One Relationships (User and Profile)
In a one-to-one relationship, each record in one table maps to a single record in another. For example, a User has a single Profile.
To enforce this relationship, make the foreign key field @unique in your schema:
model User {
id Int @id @default(autoincrement())
profile Profile?
}
model Profile {
id Int @id @default(autoincrement())
bio String
userId Int @unique
user User @relation(fields: [userId], references: [id])
}3. Many-to-Many Relationships (Post and Tags)
In many-to-many relationships, multiple records in one table map to multiple records in another. For example, a Post can have multiple Tags, and a Tag can belong to multiple Posts.
Prisma supports implicit many-to-many relationships, which automatically manage the join table under the hood:
model Post {
id Int @id @default(autoincrement())
tags Tag[]
}
model Tag {
id Int @id @default(autoincrement())
posts Post[]
}If you need to store extra fields (such as a timestamp) on the relationship itself, define an explicit join model instead:
model Post {
id Int @id @default(autoincrement())
tags PostToTag[]
}
model Tag {
id Int @id @default(autoincrement())
posts PostToTag[]
}
model PostToTag {
postId Int
tagId Int
post Post @relation(fields: [postId], references: [id])
tag Tag @relation(fields: [tagId], references: [id])
@@id([postId, tagId])
}