如何在 Typeorm NestJs 中进行 innerJoin,我是 typeorm 和 nestjs 的新手

how to innerJoin in Typeorm NestJs ,I'm newbie with typeorm and nestjs

我的产品实体

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

我的产品服务 我要加入 table 使用 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())),
    );
  }

如何将产品 table 和产品类别合并在一起?

here is the raw query " select * from products p inner join product_category pc on pc.id=p.category_id; "

我正在使用 Nestjs Typeorm+ Postgresql*

您只需指定table您要加入:

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