簡體   English   中英

如何使用條件查詢多對多關系 - TypeORM

[英]How to query a Many-to-Many relation with condition - TypeORM

具有多對多關系。 類別 - 產品

我想按類別 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})
      }
    });
  }

我閱讀了一些文檔並調試了 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})
      }
}

我希望其他人會發現它有用

您不需要在兩種方式中定義多對多,它必須在其中一種方式中定義

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM