model Favorite {
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
productId Int
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
@@unique([userId, productId])
}
상품 좋아요를 저장하는 데이터베이스 모델이 있을 때, @@unique를 통해 userId와 productId 쌍이 중복되지 않도록 설정했다.
@@unique를 설정하고 prisma generate를 할 경우 복합키가 함께 생성되는데 unique에 입력된 순서대로 _를 통해 구분된다.
async deleteFavorite(productId: number, userId: number) {
await prismaClient.favorite.delete({
where: {
userId_productId: {
userId,
productId,
},
},
});
}
이처럼 where에 userId_productId라는 복합키를 통해 삭제가 가능하다.
이러한 복합키를 사용하는 이유는 동일한 사용자가 동일한 상품에 중복으로 좋아요를 할 수 없도록 하고 데이터베이스 레벨에서 무결성을 보장하기 위함이다.
이때 복합키를 where조건으로 사용할 때 모든 userId,productId가 모두 제공되어야 한다.