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

TypeORM多对多关联关系数据查询结果聚合问题

Fixing Duplicate Results in TypeORM Many-to-Many Query

Hey there! I see you're running into an issue where your many-to-many query is returning duplicate news entries instead of a single entry with an array of tags. Let's break down why this happens and how to fix it.

Why You're Getting Duplicate Results

When you use getRawMany(), TypeORM returns the raw database rows from your JOIN query. Since each tag creates a new row paired with the same news entry, you end up with multiple copies of the news data—one for each associated tag. The getRaw* methods don't handle entity mapping or merging related data into arrays, which is why you're seeing this output.

Solution 1: Use TypeORM's Built-in Entity Query

The simplest fix is to let TypeORM handle the relationship mapping automatically with findOne (since you're querying a single news item):

const newsItem = await getRepository(News).findOne({
  where: { news_id: params.news_id },
  relations: ["tagsnews"]
});

This will return a single News entity where the tagsnews property is an array of your Tags entities—exactly the structure you want, without any manual processing.

Solution 2: Use QueryBuilder with getOne() Instead of getRawMany()

If you prefer using QueryBuilder, swap getRawMany() for getOne(). TypeORM will automatically merge the joined rows into a single entity with the tags array:

const newsItem = await getRepository(News)
  .createQueryBuilder("news")
  .leftJoinAndSelect("news.tagsnews", "tags")
  .where("news.news_id = :newsid", { newsid: params.news_id })
  .getOne();

This works because getOne()/getMany() use TypeORM's entity mapper to combine duplicate rows into a single entity, populating the tagsnews array with all associated tags.

Bonus: Manual Merging (If You Need Raw Data)

If you absolutely need to work with raw database rows (for custom formatting, etc.), you can manually merge the results:

const rawResults = await getRepository(News)
  .createQueryBuilder("news")
  .leftJoinAndSelect("news.tagsnews", "tags")
  .where("news.news_id = :newsid", { newsid: params.news_id })
  .getRawMany();

if (rawResults.length === 0) {
  return [];
}

// Merge duplicate news entries into one with tags array
const mergedResult = {
  news_news_id: rawResults[0].news_news_id,
  news_title: rawResults[0].news_title,
  news_create_date: rawResults[0].news_create_date,
  tags: rawResults.map(row => ({
    tag_id: row.tags_tag_id,
    tag_name: row.tags_name
  }))
};

return [mergedResult];

This takes the first row's news data and collects all tags from the raw rows into an array.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:43:10