Home > Enterprise >  How to delete from database where multiple conditions are met?
How to delete from database where multiple conditions are met?

Time:09-29

I'm trying to delete a row in my database using Prisma, where I want to delete it only if two conditions are met, slug and userId.

This is what I have tried to do:

const deleteComment = await prisma.favorites.delete({
      where: {
        slug: slug,
        userId: userId,
      },
    });

This is my model in schema.prisma:

model Favorites {
  id          Int     @id @default(autoincrement())
  slug        String  @db.VarChar(128)
  contentType String? @db.VarChar(128)
  userId      String
  user        User?   @relation(fields: [userId], references: [id])
}

If I remove the userId: userId, it deletes all rows containing the same slug, which is not ideal if multiple users have added the same slug.

How can I delete a row when both conditions are met?

CodePudding user response:

If you don't specify attributes sufficiently to identify a unique row (guaranteed by the schema), you should use deleteMany instead of delete.

àwait prisma.favorites.deleteMany({ where: { slug: slug, userId: userId } });
  • Related