我有一个Post实体,每个Post有N条评论。 我想引荐评论最多的帖子,但是 我也想提取Post的其他关系,例如作者(用户实体)
我可以使用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();
答案 0 :(得分:0)
要加载关系,请在查询中添加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();