【问题标题】:How to query a Many-to-Many relation with condition - TypeORM如何使用条件查询多对多关系 - TypeORM
【发布时间】:2021-11-20 00:37:40
【问题描述】:

具有多对多关系。类别 - 产品

我想按类别 id 过滤产品。

我检查了一些示例并在下面编写了这段代码,但无法使其工作

有人可以帮帮我吗? 谢谢

@Entity()
export class Product {

  @PrimaryGeneratedColumn()
  id: number;

  @ManyToMany(() => Category, {eager: true})
  @JoinTable({
    name: 'product_category'
  })
  categories: Array<Category>;
}


@Entity()
export class Category {

  @PrimaryGeneratedColumn()
  id: number;
}


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

【问题讨论】:

  • "can't make it work" 是什么意思?您收到错误消息吗?实际和预期的结果是什么?

标签: javascript node.js typescript nestjs typeorm


【解决方案1】:

你不需要在双向定义多对多 它必须在一侧定义

https://typeorm.biunav.com/en/many-to-many-relations.html#what-are-many-to-many-relations

更好的方法是使用分离实体定义

https://orkhan.gitbook.io/typeorm/docs/separating-entity-definition

【讨论】:

  • 好的,我修复了实体定义,但查询仍然不起作用。为多对多关系创建条件的方法是什么?
  • 使用此方法的更好方法:this.find({where:{categoryId: filter.categoryId},relation:['categories'])
【解决方案2】:

我阅读了一些文档并调试了 typeorm 代码并成功创建了查询:

我对多对多关系做了一些修改:

  @ManyToMany(() => Category, {eager: true})
  @JoinTable({
    name: 'product_category',
    inverseJoinColumn: {
      name: 'category_id',
      referencedColumnName: 'id'
    },
    joinColumn: {
      name: 'product_id',
      referencedColumnName: 'id'
    }
  })
  categories: Array<Category>;

和查询:

{
      relations: ['categories'],
      where: (qb: SelectQueryBuilder<Product>) => {
        qb.where('category_id = :categoryId', {categoryId: categoryId})
      }
}

希望别人会觉得有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多