TypeORM/NestJS 中的分页

Shr*_*rma 4 javascript orm backend typeorm nestjs

我必须在findAll()方法中引入分页。我真的不知道该怎么做。我尝试过,但它给出了很多错误。我使用了findAndCount()给出的方法typeorm,但我不确定它是如何工作的。

截至目前,以下方法返回所有记录。我需要一次返回10条记录。请建议我需要做什么修改。

async findAll(queryCertificateDto: QueryCertificateDto,page=1):  Promise<PaginatedResult> {
    
    let { country, sponser } = queryCertificateDto;

    const query = this.certificateRepository.createQueryBuilder('certificate');

    if (sponser) {
        sponser = sponser.toUpperCase();
        query.andWhere('Upper(certificate.sponser)=:sponser', { sponser });
    }

    if (country) {
        country = country.toUpperCase();
        query.andWhere('Upper(certificate.country)=:country', { country });
    }      
    const  certificates = query.getMany();     
    return certificates;
}
Run Code Online (Sandbox Code Playgroud)

这是PaginatedResult文件。

 export class PaginatedResult {
        data: any[];
        meta: {
          total: number;
          page: number;
          last_page: number;
        };
      }
  
Run Code Online (Sandbox Code Playgroud)

我尝试更改findAll()butwhere子句的代码给出错误。我不知道如何query.getMany()处理pagination

 const take = query.take || 10
        const skip = query.skip || 0
       
      
        const [result, total] = await this.certificateRepository.findAndCount(
            {
                where: query.getMany(),   //this is giving error
                take:take,
                skip:skip
            }
        );
        return result;
Run Code Online (Sandbox Code Playgroud)

我需要在这个方法中引入分页。任何帮助都会非常有帮助。

小智 6

Typeorm 有一个非常适合您的用例的非常好的方法findAndCount

async findAll(queryCertificateDto: QueryCertificateDto):  Promise<PaginatedResult> {

    const take = queryCertificateDto.take || 10
    const skip = queryCertificateDto.skip || 0
    const country = queryCertificateDto.keyword || ''
    const sponser = queryCertificateDto.sponser || ''
    

    const query = this.certificateRepository.createQueryBuilder('certificate');

    const [result, total] = await this.certificateRepository.findAndCount(
        {
            where: { country: Like('%' + country + '%') AND sponser: Like('%' + sponser + '%') }, order: { name: "DESC" },
            take: take,
            skip: skip
        }
    );
     
    return {
        data: result,
        count: total
    };
}
Run Code Online (Sandbox Code Playgroud)

有关 Repository 类的更多文档可以在这里找到