QueryBuilder 提取关系,例如使用 find() 方法
QueryBuilder extract relations like with find() method
我有 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();
要加载关系,请将 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();
我有 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();
要加载关系,请将 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();