无法为Prisma数据库生成种子数据:JournalEntry关联用户报错
问题:Prisma种子数据生成时JournalEntry必须关联用户的困惑
我尝试用以下代码生成Prisma数据库种子数据,但运行时提示journalEntry项必须关联用户。我对此感到困惑,因为官方文档的upsert示例并未指定用户关联。
async function main() { const food = await prisma.food.upsert({ where: { id: 1, }, create: { name: 'Protein shake', meal: 'DINNER', journalEntry: { create: { user: { // this is the problem create: {id: 1} } } }, macros: { create: { calories: 120, protein: 24, carbs: 3, fat: 0, } }, journalEntryId: 1, nutrientProfileId: 1, }, }) console.log(food); }
模型定义
model User { id Int @id @default(autoincrement()) username String @unique targetMacros NutrientProfile @relation(fields: [nutrientProfileId], references: [id]) journalEntries JournalEntry[] nutrientProfileId Int } model NutrientProfile { id Int @id @default(autoincrement()) calories Int @default(0) protein Int @default(0) carbs Int @default(0) fat Int @default(0) User User[] Food Food[] } model JournalEntry { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) journalItems Food[] notes String? @db.VarChar(255) user User @relation(fields: [userId], references: [id]) userId Int } model Food { id Int @id @default(autoincrement()) name String macros NutrientProfile @relation(fields: [nutrientProfileId], references: [id]) createdAt DateTime @default(now()) journalEntry JournalEntry? @relation(fields: [journalEntryId], references: [id]) journalEntryId Int? nutrientProfileId Int meal Meal } enum Meal { BREAKFAST LUNCH DINNER SNACK }
解决方案
问题根源
JournalEntry模型中user是必填关联字段(未加?),创建时必须绑定用户;但你创建用户时只传了id,而User模型要求username为必填唯一字段,不符合校验规则。- 手动指定的
journalEntryId:1和nutrientProfileId:1对应的记录尚未创建,会触发关联不存在的错误。
修正后的种子代码
按依赖顺序创建数据(营养配置 → 用户 → 日记条目 → 食物),确保所有关联记录提前存在:
async function main() { // 1. 创建营养配置(用户和食物都依赖它) const nutrientProfile = await prisma.nutrientProfile.upsert({ where: { id: 1 }, create: { calories: 120, protein: 24, carbs: 3, fat: 0 }, update: {}, }); // 2. 创建用户(必须包含必填的username字段) const user = await prisma.user.upsert({ where: { id: 1 }, create: { username: "test_user", nutrientProfileId: nutrientProfile.id }, update: {}, }); // 3. 创建日记条目并关联已存在的用户 const journalEntry = await prisma.journalEntry.upsert({ where: { id: 1 }, create: { userId: user.id }, update: {}, }); // 4. 创建食物并关联已有的日记条目和营养配置 const food = await prisma.food.upsert({ where: { id: 1 }, create: { name: "Protein shake", meal: "DINNER", nutrientProfileId: nutrientProfile.id, journalEntryId: journalEntry.id, }, update: {}, }); console.log("种子数据创建完成:", { nutrientProfile, user, journalEntry, food }); }
额外说明
- 官方upsert示例的场景通常是关联字段可选,或已有关联记录存在,因此无需显式创建关联;而你的模型中
JournalEntry必须绑定用户,所以必须确保关联的用户已存在。 - 避免手动指定ID创建嵌套记录,优先通过upsert确保记录存在,或依赖Prisma自动生成ID,减少关联错误。
内容的提问来源于stack exchange,提问作者Marc Fletcher
相关产品推荐
相关产品推荐

