如何在 TypeORM 中多次将 where-criteria 应用于同一字段?
How to apply where-criteria to the same field more than once in TypeORM?
我想用 TypeORM 表达这个查询:
select * from user where x > 5 and x < 10
或其他变体,例如:
select * from user where x > '2020-01-01' and x < '2020-10-10'
select * from user where x >= 5.5 and x <> 10
我该怎么做?
userRepo.find({where: {x: MoreThan(5), x: LessThan(10)}})
显然是不合法的。
基本
在 find-options page 上有一个 between 函数可以让你做到这一点
import {Between} from "typeorm";
const loadedPosts = await connection.getRepository(Post).find({
likes: Between(1, 10)
});
所以在你的情况下它是:
userRepo.find({where: {x: Between(5,10)}})
高级
如果您需要对查询进行更多控制,如您附加的示例中所示,您可以使用 raw
import {Raw} from "typeorm";
const loadedPosts = await connection.getRepository(Post).find({
currentDate: Raw(alias =>`${alias} > NOW()`)
});
创造:
SELECT * FROM "post" WHERE "currentDate" > NOW()
翻译成你的问题:
userRepo.find({
where: {
x: Raw(alias => `${alias} >= 5.5 and ${alias} <> 10`)
}
})
自定义
这可能很快就会变得太乏味,您可能想求助于更基本的 query builder 以获得更多控制
我想用 TypeORM 表达这个查询:
select * from user where x > 5 and x < 10
或其他变体,例如:
select * from user where x > '2020-01-01' and x < '2020-10-10'
select * from user where x >= 5.5 and x <> 10
我该怎么做?
userRepo.find({where: {x: MoreThan(5), x: LessThan(10)}})
显然是不合法的。
基本
在 find-options page 上有一个 between 函数可以让你做到这一点
import {Between} from "typeorm";
const loadedPosts = await connection.getRepository(Post).find({
likes: Between(1, 10)
});
所以在你的情况下它是:
userRepo.find({where: {x: Between(5,10)}})
高级
如果您需要对查询进行更多控制,如您附加的示例中所示,您可以使用 raw
import {Raw} from "typeorm";
const loadedPosts = await connection.getRepository(Post).find({
currentDate: Raw(alias =>`${alias} > NOW()`)
});
创造:
SELECT * FROM "post" WHERE "currentDate" > NOW()
翻译成你的问题:
userRepo.find({
where: {
x: Raw(alias => `${alias} >= 5.5 and ${alias} <> 10`)
}
})
自定义
这可能很快就会变得太乏味,您可能想求助于更基本的 query builder 以获得更多控制