简体   繁体   中英

Limit and skip related column in typeorm

I am trying to limit the related data while finding with query builder, but I miss the concept.

Here is my code to get the employee orders:

import { getRepository, Repository } from "typeorm";

    public async findEmployeeQuery(id : number) {
        try {
            let query = await getRepository(Employees)
            .createQueryBuilder('employee')
            .where('employee.id = :id' , {id})
            .leftJoinAndSelect('employee.customers' , 'customers')
            .getOne()
            const user = query
            return user
        } catch (error) {
            throw error
        }

    }

Now I want to limit the number of customers for each request - how can I do that?

I tried the limit and skip options but this only works with the employee, not with the joined data.

You have to make another query to limit customers:

import { getRepository, Repository } from "typeorm";

public async findEmployeeQuery(id : number) {
    try {
        let user = await getRepository(Employees)
        .createQueryBuilder('employee')
        .where('employee.id = :id' , {id});
        .getOne()

        user.customers =  await getRepository(Customers)
        .createQueryBuilder('customer')
        .where('customer.employee= :id' , {user.id});
         .limit(10) // here you set limitation you want 
        .getMany()

        return user;
    } catch (error) {
        throw error
    }

}

import { getRepository, Repository } from "typeorm";

public async findEmployeeQuery(id : number) {
    try {
        let query = await getRepository(Employees)
        .createQueryBuilder('employee')
        .where('employee.id = :id' , {id})
        .leftJoinAndSelect('employee.customers' , 'customers')
        .take(4) //lIMITS its to 4
        .skip(5) //offset 5 entitities.
        .getOne()
        const user = query
        return user
    } catch (error) {
        throw error
    }

}

I think I found a clean way for this...

Might be of help to someone because TypeORM does not support pagination in relations ( let's hope that they add soon! =) )

 let category: any = await Category.findOne({
      where: {
        id: id,
      },
    });
    // finding products linked to that category
    let products = await orm
      .createQueryBuilder("products", "p")
      .innerJoinAndSelect("p.categories", "c", "c.id = :categoryId", {
        categoryId: id,
      })
      // implementing pagination
      .skip(offset)
      .take(limit)
      .getMany();
    // Attaching the array to the Category Object
    category.products = products;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM