You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TypeORM QueryBuilder实现带where条件的内连接查询

实现方案

你需要先关联角色表,再添加对应筛选条件,以下是两种可行写法:


写法1:使用IN运算符(更简洁,推荐)

同字段多值匹配时优先用该写法,避免多or条件拼接错误:

const query = this.userRoleRepository.createQueryBuilder('usersRoles');

const users = await query
  .innerJoinAndSelect('usersRoles.role', 'role') // 关联角色表,对应原生SQL的inner join roles
  .innerJoinAndSelect('usersRoles.user', 'user')
  .where('role.role IN (:...roles)', {
    roles: ['ADMIN_ROLE', 'SUPER_ADMIN_ROLE']
  })
  .getMany();

说明:(:...roles)是TypeORM提供的数组参数展开语法,会自动生成符合SQL规范的IN查询参数。


写法2:orWhere拼接(和你提供的原生SQL逻辑完全对应)

const query = this.userRoleRepository.createQueryBuilder('usersRoles');

const users = await query
  .innerJoinAndSelect('usersRoles.role', 'role')
  .innerJoinAndSelect('usersRoles.user', 'user')
  .where('role.role = :adminRole', { adminRole: 'ADMIN_ROLE' })
  .orWhere('role.role = :superAdminRole', { superAdminRole: 'SUPER_ADMIN_ROLE' })
  .getMany();

以上两种写法生成的执行SQL和你给出的原生MySQL语句完全一致,筛选结果相同。

内容的提问来源于stack exchange,提问作者Shovon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:54:06