
在使用 prisma 进行数据库查询时,可能会遇到一个常见的问题:尽管在 prisma schema 中定义了关联关系,但查询结果中并未包含关联的数组数据。例如,shoppinglist 模型中定义了与 shoppinglistitem 的一对多关系,但在查询 shoppinglist 时,items 数组并未返回。
要解决这个问题,关键在于理解 Prisma 查询的默认行为以及如何显式地包含关联数据。
问题根源:未显式包含关联数据
Prisma 默认情况下不会自动包含所有关联数据。为了提高查询效率,Prisma 需要显式地指定需要在查询中包含哪些关联数据。
解决方案:使用 include 选项
要解决 items 数组未返回的问题,需要在 findUnique 查询中使用 include 选项,明确指定需要包含 items 数组。
以下是修改后的查询代码:
const list = await prisma.shoppingList.findUnique({
where: {
id: input.id,
},
include: {
items: true,
},
});在这个修改后的查询中,include: { items: true } 告诉 Prisma 在查询 ShoppingList 时,同时也要包含与其关联的 ShoppingListItem 数据。
代码解释:
- prisma.shoppingList.findUnique: 使用 Prisma 客户端查询 ShoppingList 模型。
- where: { id: input.id }: 指定查询条件,根据 id 查找唯一的 ShoppingList 记录。
- include: { items: true }: 关键所在,指定在查询结果中包含 items 数组,即与 ShoppingList 关联的所有 ShoppingListItem 记录。
完整示例
下面是一个完整的示例,展示了如何在 getById procedure 中使用 include 选项:
getById: publicProcedure
.input(
z.object({
id: z.string(),
})
)
.query(async ({ input }) => {
const list = await prisma.shoppingList.findUnique({
where: {
id: input.id,
},
include: {
items: true,
},
});
if (!list) throw new TRPCError({ code: "NOT_FOUND" });
return list;
}),注意事项:
- 性能影响: 包含关联数据会增加查询的复杂性和数据量,可能会影响查询性能。因此,只包含实际需要的关联数据。
- 嵌套包含: include 选项可以嵌套使用,以便包含更深层次的关联数据。例如,如果 ShoppingListItem 还有关联的 User 模型,可以这样写:include: { items: { include: { user: true } } }。
- select 选项: 除了 include 之外,还可以使用 select 选项来精确控制查询返回的字段。select 选项可以与 include 结合使用,以优化查询性能。
总结:
当在使用 Prisma 查询关联数据时,务必使用 include 选项显式地指定需要包含的关联数据。这可以确保查询结果的完整性,并避免因数据缺失而导致的问题。同时,需要注意查询性能,只包含实际需要的关联数据,并合理使用 select 选项进行优化。










