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

Typeorm QueryBuilder中isArchived条件被后续where覆盖失效求助

问题原因与解决方案

核心问题

TypeORM的QueryBuilder中,每次调用.where()会完全替换之前的WHERE子句,而非追加条件。你最初设置的isArchived = false被后续的.where()语句覆盖,导致该条件失效。

解决方法

将后续追加条件的.where()全部替换为.andWhere(),这样所有条件会以AND逻辑连接,不会覆盖初始的isArchived条件。

修改后的代码示例

// Common Get Query
const result = await this.reservationRepo
  .createQueryBuilder()
  .leftJoinAndSelect('Reservation.userId', 'userId')
  .leftJoinAndSelect('Reservation.companyId', 'companyId')
  .leftJoinAndSelect('Reservation.petId', 'petId')
  .orderBy(`Reservation.${sortBy}`, order)
  .where('Reservation.isArchived = :isArchived', { isArchived: false });

//Check req starts is cancelled and return canceled data (getting data from db)
if (getPaginationParamDto.status === GetReservationTypes.CANCELLED) {
  if (type === GetReservationTypes.COMPANY) {
    // 用andWhere追加条件,而非where
    result.andWhere('Reservation.companyId = :companyId', { companyId: searchID });
  } else {
    result.andWhere('Reservation.userId = :userId', { userId: searchID });
  }
  // 同样用andWhere追加status条件
  result.andWhere('Reservation.status = :status', { status: getPaginationParamDto.status });
}

额外提示

  • 如果需要追加OR逻辑的条件,使用.orWhere()即可
  • searchID如果是数字类型,无需用${}转成字符串,直接传入参数对象即可,TypeORM会自动处理类型绑定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:24:23