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

如何用Prisma同时统计评论的LIKED和DISLIKED交互数量?

如何同时统计单条评论的点赞与点踩数量(Prisma)

给定以下Prisma模型定义:

Comment模型

model comment {
    id          Int      @id @default(autoincrement())
    content     String
    commenterId String

    commenter            User                  @relation("commented", fields: [commenterId], references: [id])
    comment_interactions comment_interaction[]
}

CommentInteraction模型

model comment_interaction {
    userId    String
    commentId Int
    state     CommentInteraction
    user      User               @relation(fields: [userId], references: [id])
    comment   comment            @relation(fields: [commentId], references: [id])

    @@unique([userId, commentId])
}

交互状态枚举

enum CommentInteraction {
    LIKED
    DISLIKED
}

当前仅能单独统计一种交互状态的数量,需要实现同时获取LIKED和DISLIKED的计数。


解决方案

你可以在findUnique的select选项中,为两种交互状态分别定义独立的统计字段,让数据库直接计算并返回结果,无需在代码中二次处理。示例代码如下:

const comment = await prisma.comment.findUnique({
  where: { id },
  select: {
    id: true,
    content: true,
    // 统计点赞数量
    likedCount: {
      _count: {
        select: {
          comment_interactions: { where: { state: "LIKED" } }
        }
      }
    },
    // 统计点踩数量
    dislikedCount: {
      _count: {
        select: {
          comment_interactions: { where: { state: "DISLIKED" } }
        }
      }
    }
  }
})

返回结果结构

查询返回的数据结构如下:

{
  id: 1,
  content: "示例评论内容",
  likedCount: { comment_interactions: 5 },
  dislikedCount: { comment_interactions: 2 }
}

如果需要更简洁的结构,可以在查询后做简单解构处理:

const { likedCount, dislikedCount, ...commentData } = comment;
const formattedComment = {
  ...commentData,
  likedCount: likedCount.comment_interactions,
  dislikedCount: dislikedCount.comment_interactions
};

若需批量查询多条评论并统计交互数量,只需将findUnique替换为findMany即可复用上述逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:15:55