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

基于关联结果数量的GraphQL筛选/排序问题(Prisma环境)

实现方案

1. 查询拥有多篇Post的作者

在Prisma中直接通过关联计数筛选,把筛选逻辑放在数据库层面,彻底避免客户端分页和性能问题:

Prisma 服务端查询代码

const authorsWithMultiplePosts = await prisma.user.findMany({
  where: {
    // 筛选出Post数量大于1的用户
    posts: {
      _count: { gt: 1 }
    }
  },
  // 按需关联Post信息,只选需要的字段减少数据传输
  include: {
    posts: {
      select: {
        id: true,
        title: true
      }
    }
  },
  // 分页参数按需调整,避免一次性返回过多数据
  skip: 0,
  take: 10
});

客户端GraphQL查询

query GetAuthorsWithMultiplePosts($skip: Int, $take: Int) {
  authorsWithMultiplePosts(skip: $skip, take: $take) {
    id
    name
    email
    posts {
      id
      title
    }
  }
}

2. 按Post数量对作者排序

利用Prisma的关联计数排序功能,把排序逻辑下推到数据库,保证大数据量下的性能:

Prisma 服务端查询代码

const authorsSortedByPostCount = await prisma.user.findMany({
  orderBy: {
    // 按Post数量倒序排序,换成asc就是升序
    posts: {
      _count: 'desc'
    }
  },
  // 直接返回每个作者的Post数量,不用额外查询
  select: {
    id: true,
    name: true,
    email: true,
    _count: {
      select: {
        posts: true
      }
    }
  },
  // 分页参数按需设置
  skip: 0,
  take: 10
});

客户端GraphQL查询

query GetAuthorsSortedByPostCount($skip: Int, $take: Int) {
  authorsSortedByPostCount(skip: $skip, take: $take) {
    id
    name
    email
    _count {
      posts
    }
  }
}

组合场景:筛选+排序

如果需要同时筛选出有多个Post的作者并按Post数量排序,直接组合两个条件即可:

const filteredAndSortedAuthors = await prisma.user.findMany({
  where: {
    posts: { _count: { gt: 1 } }
  },
  orderBy: {
    posts: { _count: 'desc' }
  },
  select: {
    id: true,
    name: true,
    _count: { select: { posts: true } }
  },
  skip: 0,
  take: 10
});

额外说明

你的数据模型已经给Post.authorId加了索引@@index([authorId]),这会大幅提升关联计数查询的性能,无需修改模型结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:53:14