如何在Nest.js中通过TypeORM限制关联category数据的查询数量
在TypeORM查询构建器中限制关联Category数据的数量
要给关联的category设置查询数量限制,你需要通过子查询筛选每个landingSectionCategory下的指定数量数据,而非直接使用默认的leftJoinAndSelect(它会拉取全部关联数据)。以下是两种可行的实现方式:
方式一:关联时嵌入子查询限制数量
直接在leftJoinAndSelect的条件中嵌入子查询,指定要获取的category数量:
async find() { return this.landingSectionNameRepository.createQueryBuilder('landingSectionName') .leftJoinAndSelect('landingSectionName.landingSectionCategory', 'landingSectionCategory') // 关联category时通过子查询限制数量 .leftJoinAndSelect('landingSectionCategory.category', 'category', (subQuery) => { subQuery .select('category.id') .from(Category, 'category') .innerJoin('category.landingSectionCategory', 'lsc') .where('lsc.id = landingSectionCategory.id') .take(2); // 替换为你需要的限制数量,比如2条 }) .getMany(); }
方式二:窗口函数精准分组限制(适合复杂场景)
如果需要按特定排序(比如创建时间)取每个分组下的前N条category,可以结合数据库窗口函数(以PostgreSQL/MySQL 8.0+为例)实现更精确的控制:
async find() { return this.landingSectionNameRepository.createQueryBuilder('landingSectionName') .leftJoinAndSelect('landingSectionName.landingSectionCategory', 'landingSectionCategory') .leftJoinAndSelect('landingSectionCategory.category', 'category') .where((qb) => { const subQuery = qb.subQuery() .select('c.id') .from((sub) => { return sub .select(['c.id', 'lsc.id as lsc_id', `ROW_NUMBER() OVER (PARTITION BY lsc.id ORDER BY c.createdAt DESC) as rn`]) .from(Category, 'c') .innerJoin('c.landingSectionCategory', 'lsc'); }, 'ranked_categories') .where('rn <= 2') // 限制每个landingSectionCategory下最多2条category .andWhere('lsc_id = landingSectionCategory.id') .getQuery(); return `category.id IN ${subQuery}`; }) .getMany(); }
注意事项
- 将代码中的
2替换为你实际需要的限制数量; - 方式二中的
ORDER BY c.createdAt DESC可根据业务需求调整排序字段(如更新时间、优先级等); - 不同数据库的窗口函数语法略有差异,可根据你的数据库类型适配调整。
内容的提问来源于stack exchange,提问作者alireza kargar
相关产品推荐
相关产品推荐

