Prisma实战:如何在查询结果中新增帖子统计字段,获取发帖量Top10用户
解决Prisma多对多关联下的用户发帖量统计查询问题
我来帮你搞定这个需求——咱们直接用Prisma的聚合查询能力在数据库层面完成计数、排序和筛选,不用再靠前端解析JSON来处理,代码更简洁高效。
优化后的查询代码
import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() export default async function handler(req, res) { // 直接从数据库获取带发帖量的前10用户 const topUsers = await prisma.user.findMany({ // 明确指定返回的字段:用户完整信息 + 动态计算的发帖量 select: { id: true, name: true, postCount: { _count: { select: { posts: true // 对应用户模型里关联的中间表字段 } } } }, // 按发帖量降序排序 orderBy: { posts: { _count: 'desc' } }, // 只取前10位用户 take: 10 }) // 扁平化计数结构,让返回的JSON更直观(可选,但推荐) const formattedResult = topUsers.map(user => ({ id: user.id, name: user.name, postCount: user.postCount._count.posts })) res.status(200).json(formattedResult) }
关键细节解释
_count聚合函数:Prisma内置的聚合能力,可以直接在查询时计算关联表的记录数量,避免了前端循环统计的麻烦。这里我们通过postCount这个自定义字段来承载计数结果。- 排序逻辑:
orderBy里直接关联posts字段的_count值,实现按发帖量从高到低排序,完全在数据库层面完成,性能比前端排序好得多。 - 结果扁平化:默认情况下
postCount会返回嵌套结构({ _count: { posts: X } }),我们通过map把它转成直接的数字字段,让返回的JSON结构更简洁友好。
模型小提示
你的中间表命名user_to_post是有效的,不过Prisma官方推荐使用大驼峰命名(比如UsersToPosts),这样自动生成的关联字段会更符合规范,后续维护起来更顺手。比如修改后模型可以写成:
model User { id Int @id @default(autoincrement()) name String posts UsersToPosts[] } model Post { id Int @id @default(autoincrement()) name String users UsersToPosts[] } model UsersToPosts { user User? @relation(fields: [userId], references: [id]) userId Int post Post? @relation(fields: [postId], references: [id]) postId Int @@id([userId, postId]) }
这样查询里的字段名也会对应变成posts和users,风格更统一。
内容的提问来源于stack exchange,提问作者Matthieu Raynaud de Fitte
相关产品推荐
相关产品推荐

