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

TypeORM中WHERE子句的OR与AND运算符组合使用问题

在TypeORM的WHERE子句中实现OR分组条件

要实现你需要的带OR分组的查询,TypeORM有两种常用方式:

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

这种方式通过数组定义OR分支,每个数组元素内的条件为AND关系,数组元素之间为OR关系,刚好匹配你的需求:

db.getRepository(MyModel).find({
  where: [
    { type: "new", status: "A", region: "central" },
    { type: "new", status: "A", zip_code: "4831" }
  ]
})

数组里的两个对象分别对应(type="new" AND status="A" AND region="central")和(type="new" AND status="A" AND zip_code="4831"),最终组合成你需要的AND+OR逻辑。

方法二:使用QueryBuilder(更灵活,避免重复代码)

如果公共条件较多,用QueryBuilder可以避免重复书写,逻辑也更清晰:

db.getRepository(MyModel)
  .createQueryBuilder("model")
  .where("model.type = :type AND model.status = :status", { type: "new", status: "A" })
  .andWhere("model.region = :region OR model.zip_code = :zipCode", { region: "central", zipCode: "4831" })
  .getMany();

这里先通过where定义公共的AND条件,再用andWhere添加包含OR的分组条件,完全匹配目标SQL的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:18:34