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

如何在Prisma中按过滤后的关联Release计数排序,再按名称升序?

解决方案

你只需要调整orderBy配置,先按已发布(isDeployed=true)的Release计数排序,再按名称升序排序。关键是在orderBy里针对_count.releases指定和查询计数一致的过滤条件,确保排序逻辑和返回的统计值匹配。

修改后的查询代码如下:

const genresWithReleaseCount = await prisma.genre.findMany({
  select: {
    name: true,
    id: true,
    _count: { select: { releases: { where: { isDeployed: true } } } },
  },
  where: {
    name: { startsWith: "pop", mode: "insensitive" },
  },
  orderBy: [
    // 先按已发布的Release计数降序排列(要升序就改成asc)
    {
      _count: {
        releases: {
          sort: 'desc',
          where: { isDeployed: true }
        }
      }
    },
    // 再按名称升序排列
    { name: "asc" }
  ],
  take: 100,
  skip: 0,
});

关键点说明

  • orderBy是数组结构,排序优先级按数组顺序生效,第一个规则优先
  • 在_count.releases里指定where: { isDeployed: true },保证排序用的计数和返回的_count.releases数值完全一致,避免出现排序和显示计数不匹配的问题
  • 排序方向sort: 'desc'表示计数多的Genre排在前面,若需要计数少的在前,改成sort: 'asc'即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:10:41