/

Using Multiple Fields for a Unique Key in Prisma

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
2
3
4
5
6
model Like {
user Int
tweet Int
createdAt DateTime @default(now())
@@unique([user, tweet])
}

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
2
3
4
5
6
await prisma.like.delete({
where: {
user: 1,
tweet: 1
}
})

I encountered an error message:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
}

To resolve this, I had to modify the code as follows:

1
2
3
4
5
6
7
8
await prisma.like.delete({
where: {
user_tweet: {
user: 1,
tweet: 1
}
}
})

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”]