Using multiple fields for a unique key in Prisma
I ran into an issue with Prisma that made me lose a bit of time, so I’ll write how I solved it.
The model didn’t have an id field marked as @id so I added a @@unique() to say user and tweet, together, defined the unique constrain.
model Like {
user Int
tweet Int
createdAt DateTime @default(now())
@@unique([user, tweet])
}
This means we can’t have more than 1 same entries of (user, tweet) entries.
When I tried to delete an entry with
await prisma.like.delete({
where: {
user: 1,
tweet: 1
}
})
I run into an error message:
PrismaClientValidationError:
Invalid `prisma.like.delete()` invocation:
{
where: {
user: 12,
~~~~
tweet: 22
~~~~~
}
~~~~~~~~~~~
}
Argument where of type LikeWhereUniqueInput needs exactly one argument, but you provided user and tweet. Please choose one. Available args:
type LikeWhereUniqueInput {
user_tweet?: LikeUserTweetCompoundUniqueInput
}
What I had to do was change
await prisma.like.delete({
where: {
user: 1,
tweet: 1
}
})
to
await prisma.like.delete({
where: {
user_tweet: {
user: 1,
tweet: 1
}
}
})
In other words, combining the unique fields concatenating them with an underscore.
In retrospect the error message was sort of explaining this, but I didn’t get it.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.