Prisma查询未返回Schema定义的items数组问题排查
问题
使用Prisma处理数据库查询时,无论items数组为空还是包含数据,请求都无法获取该数组。Schema可正常工作,能执行CRUD操作,在Prisma Studio和Supabase中也能看到ShoppingList的items数组里有ShoppingListItem,但请求时该数组不会返回。在ShoppingList中添加的无需关联查询的testArray能正常返回。已执行以下步骤:
- 运行
pnpm prisma generate - 推送至Supabase:
pnpm prisma db push
想知道为何items数组始终无法返回,遗漏了什么?
Prisma Schema
datasource db { provider = "postgresql" url = env("DATABASE_URL") } model ShoppingListItem { id String @id @default(cuid()) name String shoppingList ShoppingList @relation(fields: [shoppingListId], references: [id]) shoppingListId String markedDone Boolean @db.Boolean @default(false) addedById String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@index([addedById, shoppingListId]) } model ShoppingList { id String @id @default(cuid()) name String items ShoppingListItem[] testArray String[] createdById String createdAt DateTime @default(now()) updatedAt DateTime @updatedAt HouseHold HouseHold? @relation(fields: [houseHoldId], references: [id]) houseHoldId String? @@index([id]) }
ShoppingList 查询代码(按ID获取)
getById: publicProcedure .input( z.object({ id: z.string(), }) ) .query(async ({ input }) => { const list = await prisma.shoppingList.findUnique({ where: { id: input.id, }, }); if (!list) throw new TRPCError({ code: "NOT_FOUND" }); return list; }),
响应示例
[ { "result": { "data": { "json": { "id": "clhnzfqy80000vv27ahbbk0xz", "name": "groceries", "testArray": [], "createdById": "user_2PFljk6joD9dEh3O2AkbDvrIOsC", "createdAt": "2023-05-14T22:23:09.104Z", "updatedAt": "2023-05-14T22:23:09.104Z", "houseHoldId": null }, "meta": { "values": { "createdAt": [ "Date" ], "updatedAt": [ "Date" ] } } } } }, { "result": { "data": { "json": { "id": "clhnzjb430003vv2795lsl7wj", "name": "test item", "shoppingListId": "clhnzfqy80000vv27ahbbk0xz", "markedDone": false, "addedById": "user_2PFljk6joD9dEh3O2AkbDvrIOsC", "createdAt": "2023-05-14T22:25:55.202Z", "updatedAt": "2023-05-14T22:25:55.202Z" }, "meta": { "values": { "createdAt": [ "Date" ], "updatedAt": [ "Date" ] } } } } } ]
解答
问题核心是Prisma的默认查询规则:Prisma不会自动查询关联模型(比如这里items对应的ShoppingListItem),而testArray是当前模型的标量数组字段,会被默认返回。
要返回关联的items数组,需要在查询中用include显式指定要包含的关联字段。修改后的查询代码如下:
getById: publicProcedure .input( z.object({ id: z.string(), }) ) .query(async ({ input }) => { const list = await prisma.shoppingList.findUnique({ where: { id: input.id, }, // 新增include,指定包含关联的items include: { items: true } }); if (!list) throw new TRPCError({ code: "NOT_FOUND" }); return list; }),
修改后,查询返回的ShoppingList对象会包含对应的items数组,无论数组为空还是有数据都会正常返回。
内容的提问来源于stack exchange,提问作者bysiuxvx
相关产品推荐
相关产品推荐

