TypeORM中一对多关系下高效统计特定分类关联文章数的方法
统计特定分类下的文章数量(避免加载全部关联文章)
直接加载blogPosts关联会拉取所有文章数据,造成性能损耗,以下是两种高效的实现方式:
1. 统计单个特定分类的文章数量
通过BlogPostRepository的count方法,直接根据分类ID过滤统计:
// 替换为目标分类的UUID const targetCategoryId = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; const postCount = await this.blogPostRepository.count({ where: { category: { ID: targetCategoryId } } });
2. 批量获取所有分类及其文章数量
使用QueryBuilder做左连接+分组聚合,一次性获取所有分类的文章数量,同时保证无文章的分类也会被返回:
const categoriesWithPostCount = await this.blogPostCategoryRepository .createQueryBuilder("category") // 左连接分类与文章关联 .leftJoin("category.blogPosts", "post") // 指定要查询的字段,包含分类信息和统计的文章数量 .select([ "category.ID", "category.text", "COUNT(post.ID) AS postCount" ]) // 按分类字段分组,确保聚合结果正确 .groupBy("category.ID, category.text") // 获取原始查询结果 .getRawMany();
返回的categoriesWithPostCount结构示例:
[ { ID: "分类UUID1", text: "前端开发", postCount: 12 }, { ID: "分类UUID2", text: "数据库", postCount: 5 }, { ID: "分类UUID3", text: "未使用分类", postCount: 0 } ]
内容的提问来源于stack exchange,提问作者Takeshi Tokugawa YD
相关产品推荐
相关产品推荐

