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?
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.