'How to do a take query with Query Builder?

I have a one to many relation on database. one productKind have many Product

ProductKind.ts

@Entity()
export class ProductKind extends BaseEntity {
  @PrimaryGeneratedColumn()
  id!: number;

  @OneToMany(() =>Product,product => product.kind,{nullable:true})
  products?: Product[];
  //...
}

Product.ts

@Entity()
export class Product extends BaseEntity {
  @PrimaryGeneratedColumn()
  id!: number;

  @ManyToOne(() => ProductKind,kind => kind.products,)
  kind:ProductKind
  //...
}

I want to get all ProductKind with limit Product in every ProductKind.I try to use this code but it just get first ProductKind, How can I edit it to right with my expect?

 const kinds = await dataSource
        .getRepository(ProductKind)
        .createQueryBuilder("productKind")
        .leftJoinAndSelect("productKind.products","products")
        .limit(realTake)
        .getMany()



Solution 1:[1]

TypeOrm doesn't support limit on leftjoint, but there's a solution to get the result excepted with multiple queries:

 //First we get ProductKind ( you can add filters you need) 
     const kinds = await dataSource
            .getRepository(ProductKind)
            .createQueryBuilder("productKind")
            .getMany();
 //now we loop on kinds to get products with the limit you want 
      for (let kind of kinds ) {
               kind.products=  await getRepository(Product)
                      .createQueryBuilder('product')
                      .where('product.kind= :id' , {kind.id});
                      .limit(10) // here you set limitation you want 
                      .getMany()
         }
   // return kinds

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Youba