typescript - 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();
解决方案
要加载关系,请添加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();
推荐阅读
- amazon-web-services - EC2 现货实例 - 没有像实例描述所说的那样分配尽可能多的 vcpu
- python - 如何合并两个都有重复的dfs
- python - 在python中使用回车和换行符的正确方法
- java - 创建一个新的 Json 文件,然后将其他 Json 文件附加到它
- angular - 向 Angular 子组件添加额外的事件绑定
- android - 如何将软件原始文件夹中的音乐设置为默认闹钟歌曲?
- javascript - onPanResponderTerminate 仅在已发布的 APP 上触发 - React Native
- r - 有没有办法只在 R 的数据框中保留重复的行?
- github - Kaggle/GitHub Notebook 不会运行 RMD 文件:上传错误
- sql - 如何允许学生在此页面中注入 DROP TABLE?