如何在TypeORM中编写符合(Z AND (X OR Y))逻辑的SQL查询
在TypeORM中实现
(Z AND (X OR Y))查询的正确方式 你之前的写法错误是因为TypeORM会将对象的键直接解析为数据库列名,0并不是有效列名,所以无法生成正确的SQL。下面提供两种可行的实现方式:
方法1:使用QueryBuilder(推荐,逻辑清晰易维护)
QueryBuilder是TypeORM中构建复杂查询的首选方式,能精准控制SQL结构:
import { getRepository } from "typeorm"; import { YourEntity } from "./entities/YourEntity"; // 替换为你的实体类 const entityRepo = getRepository(YourEntity); const queryResult = await entityRepo.createQueryBuilder("t") .where("t.Z = :zValue", { zValue: true }) .andWhere(qb => qb.where("t.X = :xValue", { xValue: true }).orWhere("t.Y = :yValue", { yValue: true })) .getMany();
这段代码会生成你需要的SQL:SELECT * FROM your_entity t WHERE t.Z = true AND (t.X = true OR t.Y = true)
也可以直接写SQL片段的方式:
const queryResult = await entityRepo.createQueryBuilder("t") .where("t.Z = :z AND (t.X = :x OR t.Y = :y)", { z: true, x: true, y: true }) .getMany();
方法2:使用FindConditions(适用于简单场景)
如果用find/findOne等快捷查询方法,可以通过嵌套条件实现逻辑:
const queryResult = await entityRepo.find({ where: { Z: true, $or: [ { X: true }, { Y: true } ] } });
注意:部分TypeORM版本或数据库驱动可能支持用or替代$or,如果$or无效可以尝试替换。
如果需要更灵活的原生SQL片段,也可以用Raw函数(注意避免SQL注入,尽量绑定参数):
import { Raw } from "typeorm"; const queryResult = await entityRepo.find({ where: { Z: true, X: Raw(alias => `${alias} = :x OR Y = :y`, { x: true, y: true }) } });
内容的提问来源于stack exchange,提问作者bakteria chan
相关产品推荐
相关产品推荐

