如何在Prisma ORM中按嵌套关联的评论总数排序作者查询
Prisma按作者所有文章的评论总数排序查询
现有数据模型包含Author、Post、Comment三个关联模型:
model Post { id String @id title String author Author comments Comment[] } model Author { id String @id name String posts Post[] } model Comment { id String @id content String post Post }
需求为查询Author列表,并按该作者所有Post的Comment总数进行排序。已知按文章数量排序的写法,但不清楚按评论总数排序的实现方式。
解决方案
要实现按作者所有文章的评论总数排序,可利用Prisma的嵌套关联计数排序语法,在orderBy中逐层指定关联字段的_count规则:
const sortedAuthors = await prisma.author.findMany({ orderBy: { posts: { comments: { _count: 'desc' // 按评论总数降序,改为'asc'则升序 } } }, // 可选:返回每个作者的总评论数 select: { id: true, name: true, totalComments: { _sum: { posts: { _count: { comments: true } } } } } })
语法说明
orderBy中通过posts.comments._count指定排序依据:Prisma会自动统计每个作者所有Post的Comment总数,并以此排序。- 若需要在查询结果中直接返回总评论数,可通过
select中的_sum嵌套_count完成聚合计算。
兼容低版本Prisma的方案
如果你的Prisma版本不支持多层嵌套计数排序,可改用原生SQL查询实现:
const sortedAuthors = await prisma.$queryRaw` SELECT a.id, a.name, COUNT(c.id) as totalComments FROM "Author" a LEFT JOIN "Post" p ON a.id = p."authorId" LEFT JOIN "Comment" c ON p.id = c."postId" GROUP BY a.id, a.name ORDER BY totalComments DESC `
内容的提问来源于stack exchange,提问作者Akron
相关产品推荐
相关产品推荐

