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

如何在TypeORM关联查询中限制关联表返回行数?

TypeORM查询一对多关联时仅返回最新一条关联数据的解决方法

你遇到的问题是take(1)没有限制关联表review_consumed的返回数量,原因是**take(1)作用的是主表Consultant的结果行数,而非关联表的行数**。当使用leftJoin后,TypeORM会将所有匹配的关联数据组装到结果对象的review_consumed数组中,所以即使加了take(1),还是会返回所有关联评论。

以下是两种可行的解决方法:

方法一:子查询关联最新评论

通过子查询先筛选出当前顾问的最新一条评论,再将这个子查询结果与主表关联:

const consultant = await consultantRepository
  .createQueryBuilder('consultant')
  .select([
    'consultant.created_at',
    'consultant.id',
    'consultant.department',
    'consultant.average_rating',
    'latestReview.id',
    'latestReview.rating',
    'latestReview.comment',
    'latestReview.created_at',
  ])
  .where('consultant.id = :id', { id })
  .andWhere('consultant.status = :status', { status: 'active' })
  // 子查询获取当前顾问的最新评论
  .leftJoin(
    (subQuery) => subQuery
      .select('review.*')
      .from(ReviewConsumed, 'review')
      .where('review.consultantId = consultant.id') // 替换为你的外键字段名
      .orderBy('review.created_at', 'DESC')
      .take(1),
    'latestReview',
    'latestReview.consultantId = consultant.id'
  )
  .getOne();

方法二:使用窗口函数(需数据库支持)

如果你的数据库支持窗口函数(如PostgreSQL、MySQL 8+),可以用ROW_NUMBER()按顾问分组并排序,仅保留每组的第一条数据:

const consultant = await consultantRepository
  .createQueryBuilder()
  .select(`
    consultant.created_at,
    consultant.id,
    consultant.department,
    consultant.average_rating,
    review.id,
    review.rating,
    review.comment,
    review.created_at
  `)
  .from(Consultant, 'consultant')
  .leftJoin(
    (subQuery) => subQuery
      .select(`
        review.*,
        ROW_NUMBER() OVER (PARTITION BY review.consultantId ORDER BY review.created_at DESC) as rn
      `)
      .from(ReviewConsumed, 'review'),
    'review',
    'review.consultantId = consultant.id AND review.rn = 1'
  )
  .where('consultant.id = :id', { id })
  .andWhere('consultant.status = :status', { status: 'active' })
  .getOne();

两种方法都能让查询结果的review_consumed字段仅包含最新的一条评论数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:47:21