typescript 限制并跳过typeorm中的相关列

fnvucqvd  于 2022-12-14  发布在  TypeScript
关注(0)|答案(3)|浏览(146)

我试图限制相关的数据,而寻找与查询构建器,但我错过了概念。
下面是我的代码来获得员工订单:

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
        }

    }

现在我想限制每个请求的客户数量-我该怎么做呢?
我尝试了限制和跳过选项,但这只适用于雇员,而不适用于连接的数据。

3j86kqsm

3j86kqsm1#

您必须进行另一个查询以限制客户:

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
    }
}
9q78igpj

9q78igpj2#

从“typeorm”导入{ getRepository,Repository };

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
    }

}
agyaoht7

agyaoht73#

我想我找到了一个干净的方法...
可能对某些人有帮助,因为TypeORM不支持关系中的分页(希望他们很快添加!=))

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;

相关问题