TypeORM中find方法如何对关联表的字段进行过滤查询
解决方案
你遇到的问题是TypeORM低版本不支持find方法直接嵌套过滤关联表字段,以下是两种可行实现方案:
方案1:使用QueryBuilder(全版本兼容,推荐)
该方案兼容性最好,同时可以精准控制关联查询逻辑,返回的groupConnection仅会保留当前指定groupId的关联数据:
async getContacts(groupId: number) { // 保留原有groupId合法性校验逻辑 await this.findOneByIdOrThrow(groupId); const contacts = await this.contactRepository .createQueryBuilder('contact') // 关联加载中间表数据对应groupConnection属性 .leftJoinAndSelect('contact.groupConnection', 'groupConnection') // 按指定groupId过滤 .where('groupConnection.groupId = :groupId', { groupId }) .getMany(); return contacts; }
方案2:TypeORM 0.3.x+ 版本find方法原生写法
如果你使用的是0.3.0及以上版本的TypeORM,可以直接用嵌套where过滤,需要注意配置relationLoadStrategy为join确保过滤生效:
async getContacts(groupId: number) { await this.findOneByIdOrThrow(groupId); const contacts = await this.contactRepository.find({ relations: ['groupConnection'], where: { groupConnection: { groupId: groupId } }, relationLoadStrategy: 'join' }); return contacts; }
原写法失效原因
TypeORM 0.2.x及更早版本的find方法不支持直接通过嵌套对象语法过滤关联表的字段,只有0.3之后的版本才支持该特性,且部分场景下需要显式指定关联加载策略为join才能正确执行过滤逻辑。
内容的提问来源于stack exchange,提问作者Luis Novo
相关产品推荐
相关产品推荐

