我正在使用Prisma w/ Postgres,并尝试与用户建立简单的一对多关系,该用户可以拥有零个或多个产品。我可以为特定用户创建1个产品,但当我尝试创建另一个产品时,我遇到了此错误:Invalid
prisma.product.create()invocation: Unique constraint failed on the fields: ('userEmail')
.我肯定遗漏了一些东西,但可能需要另一双眼睛来关注它。schema.prisma
model Product {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String
description String?
published Boolean @default(false)
user User @relation(fields: [userEmail], references: [email])
userEmail String @unique
productImageUrl String?
}
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
active Boolean?
products Product[]
}
Next.js API路径,我可以通过POST为用户创建新产品
const Index = async (_req: NextApiRequest, res: NextApiResponse) => {
const reqBody = _req.body ?? null;
if (!reqBody) res.status(200).json({ message: "No request body found" });
const product = await prisma.product.create({
data: {
user: {
connect: {
email: "xxx@x.com" // this user already exists in the DB
},
},
published: true,
name: "Test Product 3",
createdAt: new Date,
updatedAt: new Date,
}
})
res.status(200).json({ data: reqBody })
};
2条答案
按热度按时间r3i60tvu1#
愚蠢的错误。我所需要做的就是从
Product
模型上的userEmail
中删除@unique
。elcex8rz2#
不需要将product表中的外键
userEmail
定义为@uniuqe