Search code examples
typescriptforeign-keystypeormtypeorm-datamapper

QueryBuilder extract relations like with find() method


I have the Post entity each Post have N Comment. I want to extrat the posts that have most comments, but I also want to extract the other relations of the Post for example the author (User Entity)

Using the find() method I can do:

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

but this does not allow me to properly filter the data as I want (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();

What if I want to load also the relations?

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

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

Solution

  • To load the relations add leftJoinAndSelect to the query.

    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();