首页 > 解决方案 > QueryBuilder 使用 find() 方法提取关系

问题描述

我有 Post 实体,每个 Post 都有 N 条评论。我想提取评论最多的帖子,但我也想提取帖子的其他关系,例如作者(用户实体)

使用find()我可以做的方法:

postRepository.find({ relations: ["author", "headingImage"] });

但这不允许我根据需要正确过滤数据(GROUP BY)。

// UP to here I have the top posts now I have to also load the other informations
const data = await Post.createQueryBuilder("post")
  .addSelect("COUNT(comment.id)", "post_comments_cnt")
  .leftJoin("post.comments", "comments")
  .groupBy("post.id")
  .orderBy("post_comments_cnt", "DESC")
  .take(take)
  .skip(skip)
  .getMany();

如果我还想加载关系怎么办?

const relations = ["author", "headingImage"];

const data = await Post.createQueryBuilder("post")
  ...
  .loadAllRelationIds({ relations })
  .loadRelationCountAndMap("post.commentCount", "course.comments")
  .getMany();

标签: typescriptforeign-keystypeormtypeorm-datamapper

解决方案


要加载关系,请添加leftJoinAndSelect到查询中。

const data = await Post.createQueryBuilder("post")
  .addSelect("COUNT(comment.id)", "post_comments_cnt")
  .leftJoinAndSelect("post.author", "author")
  .leftJoinAndSelect("post.headingImage", "headingImage")
  .leftJoin("post.comments", "comments")
  .groupBy("post.id")
  .orderBy("post_comments_cnt", "DESC")
  .take(take)
  .skip(skip)
  .getMany();


推荐阅读