为何无法查询Prisma模型中的部分字段?
Prisma查询Good模型部分字段返回undefined的解决方法
问题
查询Good模型时,仅能获取id和title字段,userId、completed、user等字段返回undefined,但Prisma Studio中可见对应数据。
Good模型定义:
model Good { id String @id @default(cuid()) title String completed Boolean @default(false) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade) userId String }
解决方法
1. 修正查询语句的字段限制
如果查询时用select仅指定了id和title,会过滤掉其他字段。按需修改查询:
- 返回所有标量字段+关联user:
const goods = await prisma.good.findMany({ include: { user: true } })
- 手动指定需要的字段:
const goods = await prisma.good.findMany({ select: { id: true, title: true, userId: true, completed: true, createdAt: true, user: true } })
2. 显式加载关联数据
Prisma默认不自动加载关联模型,必须通过include或select声明要加载的user关联字段,否则good.user会返回undefined。
3. 确认数据库字段同步
确保已执行prisma migrate dev或prisma db push,将schema定义的字段同步到数据库,避免字段未创建导致的返回异常。
内容的提问来源于stack exchange,提问作者Graham Hagenah
相关产品推荐
相关产品推荐

