Scoped uniqueness
Prevent duplicate titles within the same author or owner.
Prisma · Const
@@unique defines a compound unique constraint across specified model fields. Every participating field must be mandatory, and Prisma adds a corresponding unique index.
Place @@unique on a model to require that the combination of listed fields is unique. Prisma creates the corresponding unique index, and the fields must be mandatory; optional fields cannot participate in the constraint.
@@unique(_ fields: FieldReference[], name: String?, map: String?, where: raw(String) | { field: value }?)| Name | Type | Description |
|---|---|---|
fields | FieldReference[] | Fields making up the compound constraint; every field must be mandatory. |
name | String? | Optional Prisma-level name for the constraint. |
map | String? | Optional database-level mapped name. |
where | raw(String) | { field: value }? | Optional raw filter expression or field-value object. |
A model-level compound unique constraint and corresponding unique index.
model Post {
id Int @id @default(autoincrement())
authorId Int
title String
@@unique([authorId, title])
}Ensures an author cannot have two posts with the same title.
Prevent duplicate titles within the same author or owner.
Represent a natural key made from multiple required columns.
Control generated constraint and index names.
@@unique defines a compound unique constraint across multiple model fields. Prisma also adds a corresponding unique index for those columns.
Follow-up: What restriction applies to the participating fields? They must all be mandatory, not optional.
Use the fields argument with a list such as @@unique([authorId, title]). The combination, rather than either field independently, must be unique.
Follow-up: How would you make the database object name explicit? Supply the name or map argument in the attribute.
A model can contain multiple @@unique blocks. If it has no @id or @@id, a @@unique block is required when it is the model's only unique constraint.
Follow-up: Can @@unique replace every identifier requirement? No; the model still needs at least one unique identifier, and the documented rule applies when it is the sole one.
@unique@@id@idunique indexcompound unique constraint