You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Prisma查询中筛选menu计数大于0的subCategories?

解决方案

要筛选出关联menu计数大于0的subCategories,你可以在subCategories的配置中添加where条件,通过两种方式实现:

方式1:检查是否存在关联的menu

利用Prisma的some操作符,判断当前subCategory是否存在至少一条关联的menu记录,这等同于计数大于0:

return await this.prisma.category.findFirst({
  where: {
    id: categoryId,
  },
  include: {
    subCategories: {
      include: {
        menu: true,
      },
      // 添加where条件过滤subCategories
      where: {
        menu: { some: {} }
      }
    },
  },
});

方式2:直接基于关联计数过滤

如果你使用的Prisma版本(v2.16及以上)支持_count过滤,可以直接指定menu的计数大于0:

return await this.prisma.category.findFirst({
  where: {
    id: categoryId,
  },
  include: {
    subCategories: {
      include: {
        menu: true,
      },
      where: {
        _count: {
          menu: { gt: 0 }
        }
      }
    },
  },
});

以上两种方式都能让查询返回的subCategories仅包含关联menu数量大于0的条目,不会再出现计数为0的情况。

内容的提问来源于stack exchange,提问作者DolDurma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:35:59