Prisma中NOT/OR条件失效及同表多_count统计问题求助
Prisma 查询问题解决方案
问题1:筛选关联Shipment的invoice_number非空且非空字符串的Order
问题分析
你当前的查询逻辑存在错误,NOT + OR的组合无法精准筛选出invoice_number同时不为null和空字符串的关联Shipment,导致查询失效。
解决方案
直接在some条件中用AND组合两个判断条件,确保关联的Shipment满足invoice_number既不为null也不为空字符串:
const result = await prisma.order.findMany({ where: { shipment: { some: { AND: [ { invoice_number: { not: null } }, { invoice_number: { not: "" } } ] } } }, });
也可以简化为更紧凑的写法:
const result = await prisma.order.findMany({ where: { shipment: { some: { invoice_number: { not: null, not: "" } } } }, });
注意:确保你的shipment模型中已正确定义invoice_number字段,否则查询会报错。
问题2:同表中实现多个_count统计
问题分析
你重复使用了select属性,对象中重复的键会被覆盖,这是导致语法报错的直接原因。Prisma支持通过自定义别名来实现不同条件的多统计需求。
解决方案
在select中定义独立的别名字段,每个字段对应一个带筛选条件的_count统计:
// 示例:从关联表统计不同条件的订单数 const result = await prisma.someParentModel.findMany({ select: { // 统计总订单数 totalOrders: { _count: { select: { order: true } } }, // 统计订单金额大于10的订单数 highValueOrders: { _count: { select: { order: { where: { order_price: { gt: 10 } } } } } } } });
如果是对单表进行聚合统计,可使用aggregate方法:
const result = await prisma.order.aggregate({ _count: { // 总订单数 total: true, // 金额大于10的订单数 highValue: { where: { order_price: { gt: 10 } } } } });
内容的提问来源于stack exchange,提问作者정재욱
相关产品推荐
相关产品推荐

