使用Prisma创建含嵌套UserCategoryStats的用户时遇TypeScript错误
问题背景
我在创建带有UserCategoryStats嵌套关联的新用户时遇到TypeScript错误,我的Prisma Schema如下:
model User { id Int @id @default(autoincrement()) username String @unique email String @unique avatar String @default("none") role Role @default(USER) password String maxScore Int @default(0) UserCategoryStats UserCategoryStats[] } model UserCategoryStats { id Int @id @default(autoincrement()) user User @relation(fields: [userId], references: [id]) userId Int category Category @relation(fields: [categoryId], references: [id]) categoryId Int correctAnswers Int @default(0) incorrectAnswers Int @default(0) totalAnswers Int @default(0) timesChosen Int @default(0) }
尝试创建用户的代码:
const newUser = await prisma.user.create({ data: { username, email, password: hashedPassword, UserCategoryStats: { create: { // 此处报错 correctAnswers: 0, incorrectAnswers: 0, totalAnswers: 0, timesChosen: 0, }, }, }, include: { UserCategoryStats: true, }, });
抛出的TypeScript错误:
Type '{ correctAnswers: number; incorrectAnswers: number; totalAnswers: number; timesChosen: number; }' is not assignable to type '(Without<UserCategoryStatsCreateWithoutUserInput, UserCategoryStatsUncheckedCreateWithoutUserInput> & UserCategoryStatsUncheckedCreateWithoutUserInput) | ... 5 more ... | undefined'.
Type '{ correctAnswers: number; incorrectAnswers: number; totalAnswers: number; timesChosen: number; }' is not assignable to type 'undefined'
问题原因
UserCategoryStats模型中定义了与Category的必填关联(categoryId是必填字段,无默认值),但创建嵌套关联时完全没提供categoryId或关联的Category记录,导致TypeScript校验不通过。
解决方法
创建UserCategoryStats时必须指定关联的分类,有两种常见方式:
方式1:关联已存在的分类
如果已有现成的Category记录,直接传入对应的categoryId:
const newUser = await prisma.user.create({ data: { username, email, password: hashedPassword, UserCategoryStats: { create: { categoryId: 1, // 替换为实际存在的分类ID // 以下字段可省略,Schema已设默认值0 // correctAnswers: 0, // incorrectAnswers: 0, // totalAnswers: 0, // timesChosen: 0, }, }, }, include: { UserCategoryStats: true, }, });
方式2:嵌套创建新分类
如果需要同时创建新的Category,使用嵌套create关联:
const newUser = await prisma.user.create({ data: { username, email, password: hashedPassword, UserCategoryStats: { create: { category: { create: { name: "默认分类" // 填写Category模型的必填字段 } } }, }, }, include: { UserCategoryStats: true, }, });
额外提示
UserCategoryStats中的correctAnswers等字段已经在Schema中设置了默认值0,创建时无需手动传入,可简化代码。
内容的提问来源于stack exchange,提问作者Mario

