You need to enable JavaScript to run this app. TypeORM如何动态生成多组配对id组成的OR组合where查询条件
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM如何动态生成多组配对id组成的OR组合where查询条件

你可以通过遍历配对ID集合,配合TypeORM的Brackets和orWhere方法动态拼接条件,以下是完整实现方案:

import { Brackets, Repository } from 'typeorm';
import { Version } from './entities/version.entity'; // 替换为你自己的Version实体路径

// 入参结构示例:const idPairs = [{id1: 1, id2: 1}, {id1:3, id2:2}, {id1:5, id2:6}]
async function getVersionsByIdPairs(idPairs: Array<{id1: number, id2: number}>, versionRepo: Repository<Version>) {
  const qb = versionRepo.createQueryBuilder('v');

  if (idPairs.length > 0) {
    qb.where(new Brackets(qb => {
      // 遍历所有配对ID,动态拼接OR条件
      idPairs.forEach((pair, index) => {
        const condition = `v.id1 = :id1_${index} AND v.id2 = :id2_${index}`;
        const params = {
          [`id1_${index}`]: pair.id1,
          [`id2_${index}`]: pair.id2
        };
        index === 0 ? qb.where(condition, params) : qb.orWhere(condition, params);
      });
    }));
  }

  // 可继续拼接其他查询条件,例如 qb.andWhere('v.isDeleted = :isDeleted`, {isDeleted: false})
  return qb.getMany();
}

说明:

  • 生成的SQL结构和需求完全匹配,所有配对条件都会被包裹在同一组括号内,避免和后续其他andWhere条件出现逻辑优先级错误
  • 所有参数采用动态命名绑定,无SQL注入风险
  • 兼容任意数量的id配对,不需要手动编写固定数量的条件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 16:54:02