Skip to content

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 my free SQL Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about database: