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

如何在TypeORM中为Comment查询附加用户的Article总数?

解决方案:在Comment查询中附加用户的文章总数

方法一:使用TypeORM内置的loadRelationCountAndMap(推荐)

这是最简洁的方式,TypeORM提供了专门的方法来加载关联关系的计数,直接将用户的文章总数映射到用户对象的属性上:

this.commentRepository
  .createQueryBuilder('comment')
  .leftJoinAndSelect('comment.commentRatings', 'commentRatings')
  .leftJoinAndSelect('comment.user', 'user')
  // 核心:加载当前用户的文章数量,映射到user.articlesCount字段
  // 注意:'user.articles'需与你的User实体中定义的文章关联属性名一致,若你用的是user.posts则替换为'user.posts'
  .loadRelationCountAndMap('user.articlesCount', 'user.articles')
  .where('comment.articleId = :id', { id })
  .select([
    'comment.id',
    'comment.comment',
    'comment.createdOn',
    'user.name',
    'user.profilePhoto',
    'user.createdOn',
    'commentRatings'
  ])
  .orderBy({ 'comment.createdOn': { order: order, nulls: 'NULLS LAST' } })
  .offset(offset)
  .limit(limit)
  .getMany()

执行后,返回的每个Comment对象中的user属性会新增articlesCount字段,存储该用户的文章总数。


方法二:通过子查询作为字段添加计数

如果需要更灵活的自定义逻辑,可以将计数作为子查询字段加入主查询:

this.commentRepository
  .createQueryBuilder('comment')
  .leftJoinAndSelect('comment.commentRatings', 'commentRatings')
  .leftJoinAndSelect('comment.user', 'user')
  // 添加子查询,计算当前用户的文章数量
  .addSelect(
    (qb) => qb
      .select('COUNT(article.id)', 'articlesCount')
      .from(Article, 'article')
      .where('article.userId = user.id'),
    'articlesCount'
  )
  .where('comment.articleId = :id', { id })
  .select([
    'comment.id',
    'comment.comment',
    'comment.createdOn',
    'user.name',
    'user.profilePhoto',
    'user.createdOn',
    'commentRatings'
  ])
  .orderBy({ 'comment.createdOn': { order: order, nulls: 'NULLS LAST' } })
  .offset(offset)
  .limit(limit)
  .getRawMany() // 若需映射到实体,需确保实体有articlesCount字段,否则用getRawMany()获取原始结果

方法三:左连接子查询表

先预计算所有用户的文章数,再通过用户ID关联到主查询:

// 先构建子查询:统计每个用户的文章数量
const userArticleCountSubQuery = this.articleRepository
  .createQueryBuilder('article')
  .select('article.userId', 'userId')
  .addSelect('COUNT(article.id)', 'articlesCount')
  .groupBy('article.userId');

// 主查询关联子查询
this.commentRepository
  .createQueryBuilder('comment')
  .leftJoinAndSelect('comment.commentRatings', 'commentRatings')
  .leftJoinAndSelect('comment.user', 'user')
  // 左连接子查询,通过用户ID关联
  .leftJoin(userArticleCountSubQuery, 'userArticleCount', 'user.id = userArticleCount.userId')
  .where('comment.articleId = :id', { id })
  .select([
    'comment.id',
    'comment.comment',
    'comment.createdOn',
    'user.name',
    'user.profilePhoto',
    'user.createdOn',
    'commentRatings',
    'userArticleCount.articlesCount'
  ])
  .orderBy({ 'comment.createdOn': { order: order, nulls: 'NULLS LAST' } })
  .offset(offset)
  .limit(limit)
  .getMany()

你之前的错误分析

  1. 第一个子查询:使用SUM(user.id)完全错误,应该用COUNT(article.id)统计文章数,且缺少按用户ID分组、与主查询用户关联的逻辑,导致SQL语法错误。
  2. 第二个子查询:在子查询中使用loadRelationCountAndMap是错误的,该方法仅适用于主查询构建器,且未添加用户ID的关联条件,引发语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:17:52