TypeORM中查询未关联指定postId的所有用户时,计数过滤提示列不存在的问题求助
TypeORM中查询未关联指定postId的所有用户时,计数过滤提示列不存在的问题求助
我最近在做一个TypeORM项目,里面User和Post是多对多的关联关系,中间表存了postId和userId这两个字段。现在我有个需求:要找出所有没有关联指定postId的用户,试了好几种方法都卡在这里了,想请教下大家怎么解决。
首先我试过用left join排除指定id,但发现有个问题——如果用户关联了多个帖子,哪怕其中一个是要排除的,只要还有其他帖子,查询结果里还是会返回这个用户,完全达不到过滤的目的。
后来我尝试用loadRelationCountAndMap来做,这是目前看起来最接近需求的方式,代码如下:
const builder = this.userRepository .createQueryBuilder('user') .loadRelationCountAndMap( 'user.userPosts', 'user.posts', 'userPosts', (qb) => { return qb.andWhere( 'userPosts.userId != :excludePostId', { excludePostId }, ); }, );
但问题来了,当我想通过builder.andWhere('userPosts > 0')来做过滤时,直接抛出了“Column not found”的错误,找不到这个列。
之后我又换了一种思路,用inner join配合分组统计来做,代码是这样的:
builder.innerJoin('user.posts', 'userPosts') .addSelect('COUNT(userPosts.userId)', 'userPostsCount') .groupBy('user.id') .addGroupBy('userPosts.userId') .addGroupBy('userPosts.postId')
我看原生查询里明明已经有userPostsCount这个列了,但当我加上builder.andWhere('userPostsCount > 0')过滤条件时,还是报同样的“Column not found”错误,实在搞不懂哪里出问题了。
有没有大佬能指点下,到底怎么才能正确实现这个需求?或者我的写法哪里有问题,怎么才能让过滤条件识别到统计出来的列?
内容来源于stack exchange
相关产品推荐
相关产品推荐

