Using Multiple Fields for a Unique Key in Prisma
I encountered an issue with Prisma that took up some of my time, so I wanted to share how I resolved it.
In my model, I didn’t have an id
field marked with @id
, so I added @@unique()
to define the user
and tweet
fields as a unique constraint.
1 | model Like { |
This means that we cannot have duplicate entries with the same (user, tweet)
combination.
When I attempted to delete an entry using the following code:
1 | await prisma.like.delete({ |
I encountered an error message:
1 | PrismaClientValidationError: |
To resolve this, I had to modify the code as follows:
1 | await prisma.like.delete({ |
In other words, I had to concatenate the unique fields with an underscore.
Looking back, the error message did provide some explanation, but it wasn’t immediately clear to me.
tags: [“Prisma”, “Prisma issues”, “unique key”, “database constraints”]