【问题标题】:how to innerJoin in Typeorm NestJs ,I'm newbie with typeorm and nestjs如何innerJoin in Typeorm NestJs,我是typeorm和nestjs的新手
【发布时间】:2021-04-23 13:02:23
【问题描述】:

我的产品实体

@Entity({ name: 'products' })
export class ProductEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  product_name: string;

  @Column({ nullable: true, default: 0 })
  unit_qty: number;

  @Column({ nullable: true, default: 0 })
  unit_price: number;

  @Column()
  size: number;

  @Column({ nullable: true })
  cost: number;

  @Column({ type: 'boolean', default: false })
  status: boolean;

  @ManyToOne(
    () => ProductCategoryEntity,
    (productCategoryEntity) => productCategoryEntity.product,
  )
  @JoinColumn({ name: 'category_id', referencedColumnName: 'id' })
  category: ProductCategoryEntity;

  @Column()
  category_id: number;

  @BeforeInsert()
  async lowerCase() {
    this.product_name = this.product_name.toLowerCase();
  }
}

**My Product Category Entity**

@Entity({ name: 'product_category' })
export class ProductCategoryEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  category: string;

  @OneToMany(() => ProductEntity, (productEntity) => productEntity.category)
  product: ProductEntity;

  @BeforeInsert()
  async lowerCase() {
    this.category = this.category.toLowerCase();
  }
}

我的产品服务 我想使用 createQueryBuilder 连接表的代码有什么例子吗?

findAll(option: IPaginationOptions): Observable<Pagination<ProductEntity>> {
    const queryBuilder = this.productRepo
      .createQueryBuilder('product')
      .innerJoinAndSelect();

    return from(paginate<ProductEntity>(queryBuilder, option)).pipe(
      map((products) => products),
      catchError(() => throwError(new InternalServerErrorException())),
    );
  }

如何将产品表和产品类别连接在一起?

这里是原始查询“ select * 从产品 p 内连接product_category pc on pc.id=p.category_id; "

我正在使用 Nestjs Typeorm+ Postgresql*

【问题讨论】:

    标签: postgresql pagination inner-join nestjs typeorm


    【解决方案1】:

    您只需要指定要加入的表:

    findAll(option: IPaginationOptions): Observable<Pagination<ProductEntity>> {
    const result = await this.productRepo
      .createQueryBuilder('product')
      .innerJoinAndSelect('product.category','category')
      .getMany();
     console.log(result);  // check the result
    return from(paginate<ProductEntity>(queryBuilder, option)).pipe(
      map((products) => products),
      catchError(() => throwError(new InternalServerErrorException())),
    );
     }
    

    欲了解更多信息,请访问Inner and left joins

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2022-01-11
      • 2020-10-19
      • 2021-04-28
      • 2019-04-03
      • 2020-12-22
      • 1970-01-01
      • 2020-12-20
      • 2019-10-31
      相关资源
      最近更新 更多