Referential actions
Referential actions determine what happens to a record when your application deletes or updates a related record.
From version 2.26.0, you can define referential actions on the relation fields in your Prisma schema. This allows you to define referential actions like cascading deletes and cascading updates at a Prisma ORM level.
Version differences
- If you use version 3.0.1 or later, you can use referential actions as described on this page.
- If you use a version between 2.26.0 and 3.0.0, you can use referential actions as described on this page, but you must enable the preview feature flag
referentialActions. - If you use version 2.25.0 or earlier, you can configure cascading deletes manually in your database.
In the following example, adding onDelete: Cascade to the author field on the Post model means that deleting the User record will also delete all related Post records.
model Post {
id Int @id @default(autoincrement())
title String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId Int
}
model User {
id Int @id @default(autoincrement())
posts Post[]
}
If you do not specify a referential action, Prisma ORM uses a default.
If you upgrade from a version earlier than 2.26.0:
It is extremely important that you check the upgrade paths for referential actions section. Prisma ORM's support of referential actions removes the safety net in Prisma Client that prevents cascading deletes at runtime. If you use the feature without upgrading your database, the old default action - ON DELETE CASCADE - becomes active. This might result in cascading deletes that you did not expect.
What are referential actions?
Referential actions are policies that define how a referenced record is handled by the database when you run an update or delete query.
Referential actions on the database level
Referential actions are features of foreign key constraints that exist to preserve referential integrity in your database.
When you define relationships between data models in your Prisma schema, you use relation fields, which do not exist on the database, and scalar fields, which do exist on the database. These foreign keys connect the models on the database level.
Referential integrity states that these foreign keys must reference an existing primary key value in the related database table. In your Prisma schema, this is generally represented by the id field on the related model.
By default a database will reject any operation that violates the referential integrity, for example, by deleting referenced records.