TypeORM有条件的查询多对多关系。

问题描述 投票:0回答:1

比方说,我有一个 colors 桌子和一个 items 桌子,有 @ManyToMany 这2个表之间的关系(一个项目可以有很多颜色,一个颜色可以有很多项目)。

使用TypeORM,我想得到所有只匹配一个或多个提供的颜色的项目。如果一个项目有一个额外的颜色,在查询中没有指定,它不应该被检索。

const matchingColors = ['green', 'blue'];
const query = await this.itemRepository
  .createQueryBuilder('item')
  .innerJoin('item.colors', 'color', 'color.name IN (:...matchingColors)', { matchingColors })
  .getMany();

在上面的例子中,我想得到 匹配的项目 matchingColors 数组,所以所有具有绿色,或蓝色,或绿色和蓝色的项目。所以,如果一个项目有蓝色和红色,或者只有红色(或者没有颜色),它应该被排除在结果之外。

目前,我没有找到合适的方法。我上面的例子中的查询不能正常工作。我的梦想是只用1个SQL查询就能实现。谢谢您的帮助!

mysql typescript many-to-many typeorm
1个回答
0
投票

试试这个。

const matchingColors = ['green', 'blue'];
const items = await this.itemRepository
  .createQueryBuilder('item')
  .innerJoinAndSelect(
      'item.colors',
      'color',
      '"color"."name" IN (:...matchingColors)',
      { matchingColors }
   )
  .getMany();
© www.soinside.com 2019 - 2024. All rights reserved.