如何在NestJS+TypeORM的关联查询中添加take和skip?
在NestJS + TypeORM中为关联查询添加分页(take/skip)参数
你预期的写法不符合TypeORM的语法规范,以下是两种可行的实现方式:
方式一:使用TypeORM 0.3+的嵌套关联配置
TypeORM 0.3及以上版本支持在relations配置中直接嵌套分页参数,无需在根级单独声明关联字段的分页配置。示例代码如下:
// 以findOne查询为例 const targetEntity = await this.yourEntityRepository.findOne({ where: { id }, relations: { photos: { take: 10, skip: 5 } } });
使用该方式的前提:
- TypeORM版本需≥0.3.0
- 实体间已正确定义关联关系(比如主实体用
@OneToMany(() => Photo, photo => photo.entity),Photo实体用@ManyToOne(() => Entity, entity => entity.photos))
方式二:使用QueryBuilder(兼容所有TypeORM版本)
如果你的TypeORM版本较低,或者需要更复杂的查询逻辑,推荐使用QueryBuilder实现关联表的分页查询。示例代码如下:
const targetEntity = await this.yourEntityRepository .createQueryBuilder('entity') .where('entity.id = :id', { id }) // 通过子查询筛选指定分页范围的photos .leftJoinAndSelect( (subQuery) => subQuery .select('photo') .from(Photo, 'photo') .where('photo.entityId = entity.id') .take(10) .skip(5), 'photos', 'photos.entityId = entity.id' ) .getOne();
注意事项:
- 替换代码中的
yourEntityRepository、Entity、Photo为你实际的仓库类和实体类名 photo.entityId需替换为Photo实体中关联主实体的外键字段名- 若需查询多个主实体并分别对每个主实体的关联photos分页,该方式同样适用
内容的提问来源于stack exchange,提问作者Thiha Kyaw
相关产品推荐
相关产品推荐

