如何在TypeORM更新时用多条件检查数据重复(排除自身)
解决TypeORM重复键名错误及实现更新时重复数据检查
错误原因
你编写的对象字面量中重复定义了productNo属性,JavaScript/TypeScript不允许对象存在多个同名属性,因此触发An object literal cannot have multiple properties with the same name.错误。
正确实现方式
以下几种方案都能实现你需要的「排除当前数据后检查新编号是否重复」的逻辑:
方案1:使用TypeORM的And操作符
导入And和Not操作符后,将两个条件组合到同一个productNo字段下:
import { And, Not } from 'typeorm'; const productExist: number = await this.productRepository.countBy({ productNo: And( updateProductDto.productNo, Not(currentProduct.productNo) ) });
方案2:使用QueryBuilder(更贴近原生SQL)
通过QueryBuilder构建查询逻辑,直观对应你想要的SQL语句:
const productExist: number = await this.productRepository .createQueryBuilder('product') .where('product.product_no = :newNo', { newNo: updateProductDto.productNo }) .andWhere('product.product_no != :currentNo', { currentNo: currentProduct.productNo }) .getCount();
方案3:使用数组形式的条件
TypeORM支持将多个条件以数组形式传入countBy,数组内的条件默认以AND关系组合:
const productExist: number = await this.productRepository.countBy([ { productNo: updateProductDto.productNo }, { productNo: Not(currentProduct.productNo) } ]);
结果处理
上述代码执行后,productExist会返回符合条件的记录数:
- 返回0:无重复数据或修改后编号与原编号一致
- 返回大于0的数值:存在重复数据
内容的提问来源于stack exchange,提问作者Hikaru Shindo
相关产品推荐
相关产品推荐

