Overview
Relations define how models are connected to each other. Prisma supports three types of relations: one-to-one, one-to-many, and many-to-many.One-to-One Relations
A one-to-one relation connects one record to exactly one record in another model.Basic One-to-One
- The side with the foreign key has
@relation(fields: [...], references: [...]) - The other side has an optional field (
?) or is a list - Use
@uniqueon the foreign key field
One-to-One with Cascade Delete
One-to-Many Relations
A one-to-many relation connects one record to multiple records.Basic One-to-Many
One-to-Many with Multiple Relations
Referential Actions
Cascade- Delete/update related recordsRestrict- Prevent operation if related records existNoAction- Do nothing (may cause database error)SetNull- Set foreign key to nullSetDefault- Set foreign key to default value
Many-to-Many Relations
Many-to-many relations connect multiple records on both sides.Implicit Many-to-Many
Prisma creates a join table automatically:Explicit Many-to-Many
Define the join table explicitly for more control:- Add extra fields to the relation (timestamps, metadata)
- Custom naming for the join table
- Composite primary keys
- Additional constraints
Self Relations
Models can reference themselves.One-to-Many Self Relation
Many-to-Many Self Relation
Multiple Relations Between Same Models
Use relation names to distinguish multiple relations:Composite Foreign Keys
Relations can use composite keys:Complete Examples
Blog Platform
Social Network
E-commerce
Best Practices
- Always define both sides of a relation
- Use meaningful relation names for multiple relations between the same models
- Add appropriate referential actions (
onDelete,onUpdate) - Use
Cascadecarefully - it permanently deletes related data - Index foreign key fields for better query performance
- Use explicit many-to-many when you need extra fields on the relation
- Consider using self-relations for hierarchical or network data
- Use composite keys when business logic requires it
- Name your relations clearly when you have multiple relations
- Document complex relation logic with comments