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

如何在TypeORM Repository中组合使用OR与AND查询条件

TypeORM实现指定SQL查询逻辑

目标SQL语句

SELECT * 
FROM tbl_orders 
WHERE branch_id = 1 
  AND (seller_id = 11 OR seller_id IS NULL);

当前代码(待修改)

const result = await this.productRepository.find({
  where: { branch_id:1, seller_id:11},
  relations: ['seller']
});

解决方案

TypeORM的find方法支持在where中传入条件数组实现OR逻辑,结合固定AND条件,有两种实现方式:

方法一:使用find方法的条件数组

const result = await this.productRepository.find({
  where: [
    { branch_id: 1, seller_id: 11 },
    { branch_id: 1, seller_id: null }
  ],
  relations: ['seller']
});

数组内的两个对象是OR关系,每个对象内部是AND关系,完全匹配目标SQL的逻辑:(branch_id=1 AND seller_id=11) OR (branch_id=1 AND seller_id IS NULL)。

方法二:使用QueryBuilder(适配复杂查询场景)

如果后续查询逻辑更复杂,推荐用QueryBuilder构建,逻辑更直观:

const result = await this.productRepository
  .createQueryBuilder('order')
  .leftJoinAndSelect('order.seller', 'seller') // 对应原代码的relations: ['seller']
  .where('order.branch_id = :branchId', { branchId: 1 })
  .andWhere('order.seller_id = :sellerId OR order.seller_id IS NULL', { sellerId: 11 })
  .getMany();

这种写法完全复刻目标SQL的结构,可读性和扩展性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:45:54