【发布时间】:2021-12-27 22:26:12
【问题描述】:
我在 Mysql 中使用 Prisma ORM,我创建了三个模型:用户、帖子和评论:
model User {
id Int @id @default(autoincrement())
name String @db.VarChar(255)
email String
posts Post[]
profile Profile?
comments Comment[]
}
model Post {
id Int @id @default(autoincrement())
title String @db.VarChar(255)
content String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
author User @relation(fields: [authorId], references:[id])
authorId Int
comments Comment[]
}
model Comment {
id Int @id @default(autoincrement())
content String
post Post @relation(fields: [postId], references:[id])
postId Int
author User @relation(fields: [authorId], references:[id])
authorId Int
}
我想使用代码为 PostId=3 的帖子添加其他评论:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function main() {
await prisma.comment.create({
data:{
content: 'an other comment on post 3',
postId: 3,
authorId: 2,
}
})
};
main().catch(e=>console.log(e))
我收到一个错误:
PrismaClientKnownRequestError:
无效的prisma.comment.create() 调用
/home/houcem/Desktop/projects/Blog/test.ts:6:26
3 const prisma = new PrismaClient();
4
5 async function main() {
→ 6 await prisma.comment.create(
Unique constraint failed on the constraint: `Comment_postId_key`
【问题讨论】:
-
能否分享一下 prisma 查询的代码(问题发生在哪里)?了解
user和post表中存在哪些数据可能也会有所帮助。 -
我在下面的评论中发布了详细信息
-
您好,我会看看,但您应该使用您刚刚提供的详细信息来编辑您的问题。 “答案”是为了回答问题,而不是为了添加细节(应该直接在问题中)。
-
我会的,谢谢
-
我尝试复制您的确切设置(包括数据)和您不久前提供的查询(您不小心将其作为答案发布)。创建多个 cmets 似乎没有问题。您确定您使用的是有效的
postId和authorId字段吗?我还建议使用connectoperator 而不是直接传递postId和authorId。