Home > Enterprise >  How to query a Many-to-Many relation with condition - TypeORM
How to query a Many-to-Many relation with condition - TypeORM

Time:09-28

Has a many to many relationship. Category - Product

I want to filter the products by category id.

I checked some examples and wrote this code below, but can't make it work

Can somebody help me out? thanks

@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})
      }
    });
  }

CodePudding user response:

you don't need to be define many-to-many in two way side its must define in one of side

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

and better way use the Separating Entity Definition

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

CodePudding user response:

I read some documentation and debugged the typeorm code and successfully created the query:

I made some modification on the many to many relation:

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

and the query:

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

I hope someone else will find it useful

  • Related