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.