좋아요 기능을 구현하던 중 PrismaClientValidationError 오류가 발생
이유가 무엇일까 찾아보자
//schema.prisma
model Likes{
id Int @id @default(autoincrement())
like Boolean @default(true)
userId Int
postId Int
createdAt DateTime @db.DateTime(0) @default(now())
updatedAt DateTime @db.DateTime(0) @updatedAt
Users Users @relation(fields: [userId], references: [id], onDelete: Cascade)
Posts Posts @relation(fields: [postId], references: [id], onDelete: Cascade)
}
위는 모델을 설정한 코드이고 아래는 좋아요를 수정하는 코드이다
const a = await prisma.likes.update({
where: { userId, postId },
data: { like: false },
});
where에서 문제가 생겨서 찾아본 결과
where 은 단일 필드(primary key) 또는 복합 고유 필드(unique constraint)가 들어가야 한다
그래서 userId + postId의 조합이 유일함을 보장하지 않으면 update가 불가능한것
@@unique([userId, postId] 를 추가해서 userId + postId의 조합이 유일함을 보장해야한다
내 likes 테이블에서 userId + postId의 조합은 하나 밖에 없으므로 모델에 추가해주었다
복합키를 사용하는 수정된 코드
const a = await prisma.likes.update({
where: { userId_postId: { userId, postId } },
data: { like: false },
});