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

如何用TypeORM Query Builder实现带分组的多条件WHERE查询

TypeORM Query Builder实现带括号的WHERE条件逻辑

你需要实现的目标SQL为:

WHERE ( statement1 OR statement2 ) AND statement3

你之前的代码写法会因为SQL运算符优先级(AND优先级高于OR),生成不符合预期的SQL:

WHERE statement1 OR statement2 AND statement3

正确实现方式

方法一:使用嵌套Query Builder回调

通过在where方法中传入回调函数,将statement1和statement2包裹为一组条件:

Entity.createQueryBuilder()
  .where(qb => {
    return qb.where(statement1).orWhere(statement2);
  })
  .andWhere(statement3);

方法二:直接编写带括号的条件字符串

如果条件是固定的字符串,可以直接传入带括号的条件语句:

Entity.createQueryBuilder()
  .where("(statement1 OR statement2)")
  .andWhere(statement3);

这两种方式都会生成你需要的带括号的WHERE逻辑,确保statement1和statement2先执行OR运算,再和statement3执行AND运算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:40:22