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

如何用Prisma筛选拥有超5本书的作者?适配Next14分页

解决Prisma一对多关联筛选+分页问题

要筛选关联书籍数量超过5本的作者,同时保留分页逻辑并获取关联书籍数据,你需要直接在Prisma查询的where条件中利用关联计数进行数据库层面的筛选,而非查询结果后用JS过滤。

正确查询代码

const authors = await prisma.author.findMany({
  take: limit,
  skip: (page - 1) * limit,
  // 数据库层面直接筛选书籍数量>5的作者
  where: {
    books: {
      _count: {
        gt: 5
      }
    }
  },
  select: {
    id: true,
    name: true,
    books: {
      select: {
        id: true,
        bookName: true,
        publishedDate: true,
      },
    },
    _count: {
      select: { books: true }
    }
  }
});

关键说明

  • where.books._count.gt: 5是让数据库先筛选出符合条件的作者,后续的take和skip分页逻辑基于筛选后的结果集执行,不会出现前端过滤导致的分页数据丢失问题。
  • 该查询可以同时获取每个作者的关联书籍列表以及准确的书籍计数,完全匹配需求。

补充:计算分页总页数

如果需要生成分页导航,可单独查询符合条件的作者总数:

const totalQualifiedAuthors = await prisma.author.count({
  where: {
    books: {
      _count: {
        gt: 5
      }
    }
  }
});
const totalPages = Math.ceil(totalQualifiedAuthors / limit);

内容的提问来源于stack exchange,提问作者Muhtasim Fuad Showmik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:40:21