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

TypeORM多对多关系条件查询:如何根据分类ID筛选对应商品

问题排查及修复方案

现有代码错误点

  • join配置格式错误:主表别名未正确声明,也未指定要关联的Product实体下的categories属性,无法正确关联中间表查询
  • 变量引用错误:过滤条件中使用了不存在的filter对象,应该直接调用方法传入的categoryId参数
  • (可选规范问题)Category实体未配置多对多反向关联,不符合TypeORM多对多关联的编写规范

修复后代码

实体类调整

Category实体补充反向关联即可,Product实体原有配置无需修改:

@Entity()
export class Category {
  @PrimaryGeneratedColumn()
  id: number;

  // 新增多对多反向关联,@JoinTable已在Product侧配置,此处不需要重复加
  @ManyToMany(() => Product, product => product.categories)
  products: Array<Product>;
}

查询方法修正

提供两种可行写法,按需选择即可:

写法1:基于原有find方法调整

findProducts(categoryId: number) {
  return this.find({
    alias: 'product',
    join: {
      alias: 'product',
      leftJoinAndSelect: {
        category: 'product.categories'
      }
    },
    where: (qb) => {
      qb.where('category.id = :categoryId', { categoryId })
    }
  });
}

写法2:更推荐的QueryBuilder写法(多关联场景逻辑更清晰)

findProducts(categoryId: number) {
  return this.createQueryBuilder('product')
    .leftJoinAndSelect('product.categories', 'category')
    .where('category.id = :categoryId', { categoryId })
    .getMany();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:39:04