1

I don't want duplicate rows to be added to the database from users who have already clicked the like. What should I do?

I've seen it said to use upsert, but isn't upsert create if it doesn't exist and update if it exists?

If you update, there will be no duplicates, but doesn't it waste database resources anyway?

dontknowhy
  • 2,480
  • 2
  • 23
  • 67
  • 1
    Use a proper unique constraint (e.g. on user and the object you assign the like to)... If there is nothing to be updated (like a timestamp), you don't need to you upsert, you can also use insert and let it fail. – some-user Oct 19 '22 at 09:17
  • @some-user Hi really thanks, I have liked table and it has three column, it own id, post, user, could you describe as prisma.schema as answer please?? I know how to make only one column unique, but I don't know how to make each different column unique as a set. @@unique([postId, userId]) <-- is this correct? – dontknowhy Oct 19 '22 at 12:31

1 Answers1

1

Here's the schema which you would need to define a constraint in which a user can like a post only one time.

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id    Int    @id @default(autoincrement())
  name  String
  email String @unique
  posts Post[]
  Like  Like[]
}

model Post {
  id        Int     @id @default(autoincrement())
  title     String
  published Boolean @default(true)
  author    User    @relation(fields: [authorId], references: [id])
  authorId  Int
  Like      Like[]
}

model Like {
  id     Int  @id @default(autoincrement())
  post   Post @relation(fields: [postId], references: [id])
  postId Int
  user   User @relation(fields: [userId], references: [id])
  userId Int

  @@unique([postId, userId])
}

Here a compound unique key is configured on the combination of postId and userId in Like Table.

If a user tries to like a post second time, the database would throw a unique constraint failed error.

Nurul Sundarani
  • 5,550
  • 3
  • 23
  • 52