如何使用 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 做到这一点?
首先,我发现您没有执行查询。因此,在查询链的末尾添加
.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
。我希望您添加一些用户信息和分页参数,例如 page
、rowsPerPage
和 orderBy
。如果没有,那就是解决问题的第二点:您需要解析查询参数并将其放入您的dto
(因为您使用来自dto
的这些参数)
希望对您有帮助
在纯 TypeORM 中执行此操作的最佳方法如下:
const getPaginatedAndFilteringUsers = async (
dto: PaginationUserDto,
): Promise<User[]> => {
const [user, count] = await User.findAndCount({
order: { id: "DESC" },
skip: dto.rowsPerPage,
take: dto.page,
});
return paginatedUserInfo({
user: user,
totalCount: count,
});
};
totalCount 不被视为分页结果 返回完整行数