首页 > 解决方案 > TypeScript 和 TypeORM 中的分页和过滤

问题描述

如何使用 typeorm 创建分页和过滤功能?

我使用queryBuilder()但我不知道如何创建一个函数来将结果分成页面并在一页上产生结果。

我尝试这样:

  async getPaginatedAndFilteringUsers(dto: PaginationUserDto): Promise<User[]> {
    
    const user = this.conn.getRepository(Employee)
      .createQueryBuilder('user ')
      .orderBy('user.id', dto.order)
      .skip(dto.rowsPerPage)
      .take(dto.page);

    return user;
  }

但它不起作用。

我想用这样的参数创建一个函数: localhost:3000/user?page=1&rowsPerPage=15&orderBy=DESC

有人可以告诉我如何用 typeorm 做到这一点吗?

非常感谢所有帮助:)

标签: javascripttypescriptpaginationnestjstypeorm

解决方案


首先,我看到您没有执行查询。因此,.getMany()在查询链的末尾添加:

getPaginatedAndFilteringUsers(dto: PaginationUserDto): Promise<User[]> {
    return this.conn.getRepository(Employee)
      .createQueryBuilder('user')
      .orderBy('user.id', dto.order)
      .skip(dto.rowsPerPage)
      .take(dto.page)
      .getMany();
}

其次,我不知道你放了什么PaginationUserDto。我希望,你把一些用户的信息和分页参数,比如pagerowsPerPageorderBy。如果没有,这是解决问题的第二点:您需要解析查询参数并将其放入您的dto(因为您使用这些参数来自dto


我希望它会有所帮助


推荐阅读