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

如何在TypeORM的find()方法中用重复键构建AND条件查询

如何在TypeORM的find()中实现同一字段的多AND条件查询

你遇到的报错是因为JavaScript/TypeScript不允许对象字面量存在重复的属性名,你写的where对象里重复定义了productId,导致语法错误。以下是两种正确实现同一字段多AND条件查询的方式:

方法一:使用TypeORM的And逻辑操作符

直接通过And函数组合两个条件,将同一字段的多个约束合并:

import { And, Not } from "typeorm";

const salesList = await this.salesRepository.find({
  where: {
    productId: And(productId, Not(0))
  }
});

这段代码会生成productId = ? AND productId != 0的SQL查询,完全匹配你的需求。

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

如果后续需要扩展更复杂的查询逻辑,推荐使用QueryBuilder,逻辑更清晰直观:

const salesList = await this.salesRepository
  .createQueryBuilder("sale")
  .where("sale.productId = :productId", { productId })
  .andWhere("sale.productId != :zero", { zero: 0 })
  .getMany();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:33:11