One-to-one and one-to-many relations
Connect a relation field to a scalar foreign key and referenced identifier.
Prisma · Const
@relation defines metadata for a Prisma relation field, including how scalar foreign keys map to referenced fields. It also supports relation naming and referential actions.
@relation annotates a relation field with metadata Prisma needs to connect models. It can identify the participating scalar fields, referenced fields, relation names, and database referential actions; its exact arguments depend on the relation shape and connector.
@relation(name?, fields?, references?, onDelete?, onUpdate?)| Name | Type | Description |
|---|---|---|
name | String | Optional relation name used to disambiguate relations; it must match on both sides and cannot be empty. |
fields | FieldReference[] | Scalar fields on the current model that store the relation foreign key. |
references | FieldReference[] | Fields on the related model referenced by the relation foreign key. |
onDelete | ReferentialAction | Database action applied when a related record is deleted. |
onUpdate | ReferentialAction | Database action applied when a related record is updated. |
No runtime return value; @relation is a Prisma schema attribute.
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
author User @relation(fields: [authorId], references: [id])
authorId Int
}The relation field points to User, while fields and references connect the scalar foreign key to the referenced identifier.
Connect a relation field to a scalar foreign key and referenced identifier.
Give two relations between the same models distinct identities.
Describe a model related to itself.
Customize deletion or update behavior for related records.
@relation adds metadata to a relation field. In a typical one-to-many relation, fields identifies the local scalar foreign key and references identifies the target field it points to.
Follow-up: How would you model two relations between the same models? Add the name argument to both relation fields and use the same nonempty name on each side.
The attribute is needed for one-to-one and one-to-many relations on one side together with the corresponding relation scalar. It is also required when relations need disambiguation, for self-relations, and for MongoDB many-to-many relations.
Follow-up: What must a one-to-one foreign key have? It needs a unique constraint so one related record cannot be linked to multiple records.
A fully annotated relation commonly looks like author User @relation(fields: [authorId], references: [id]). The scalar authorId stores the foreign-key value, while id is the referenced field on User.
Follow-up: Which database concepts correspond to this mapping? It corresponds to foreign-key and references constructs in the database.
relationsrelation fieldsrelation scalar fieldsreferential actionsrelation modes