Referential Actions
Referential actions decide what happens to referencing records when the referenced record is deleted, or when its primary key changes. They are declared on the owning side of a relation.
Definition
onDelete and onUpdate are options of @relation. onDelete defaults to Restrict; omitted onUpdate generates RESTRICT.
| Action | Behavior |
|---|---|
Restrict | Rejects the operation while references exist |
NoAction | Rejects the operation while references exist, checked at the end of the statement |
Cascade | Deletes the referencing records, or updates their foreign keys |
SetNull | Sets the foreign key to NULL; for optional relations |
Example
ts
model Post {
id: int @id @auto
title: string
author: User @relation(onDelete: Cascade)
editor?: User @relation(onDelete: SetNull)
}1
2
3
4
5
6
2
3
4
5
6
Deleting a user deletes the posts they authored and clears the editor reference on the posts they edited. A user still referenced as an editor can be deleted, because SetNull needs a nullable column.
Notes
- The database carries out referential actions, so they apply to raw SQL as well, and join table links are always deleted together with either side.
- Soft delete only sets a deletion time and triggers no referential action.
Next Steps
- Foreign Key Fields: bind the column yourself
- Soft Delete: hide rows without deleting them