node.js - TypeORM : 使用嵌套的 AND 和 OR 生成查询
问题描述
我正在使用 NodeJS + TypeORM + PostgreSQL
我发现很难根据我的要求生成查询。
我需要生成以下查询:
select * from clinics where status = 1 and (last_sync_date < x or last_sync_date is null)
这里x是当前日期 - 10 天。
我尝试了以下查询:
let now = Date();
now.setDate(now.getDate() - 10);
let clinics = await clinicRepo.find({
where: [
{ status: 1, last_sync_date: LessThan(now) },
{ last_sync_date: IsNull() }
]
});
但结果是这样的:
select * from clinics where (status = 1 and last_sync_date < x) or last_sync_date is null;
我需要在上面的代码中更改什么?
我想使用find以便我也可以加载关系。
解决方案
您可以通过使用 js 条件创建查询然后将其分配给 FindConditions 来解决此问题。
例如:
const whereCondition = testResultId ?
{patientId, id: Not(testResultId), clinicId} :
{patientId, clinicId}
const tr = await TestResult.findOne({
where: whereCondition,
})
或者您可以使用 Raw 运算符:
let clinics= await clinicRepo.find({
where : [
{status: 1,
last_sync_date: Raw(alias => `(${alias} < ${now} OR ${alias} IS NULL)`}
]
});
推荐阅读
- reactjs - 将 prevState 参数与 setState 中的 map 函数反应
- x86 - 使用 lipo 创建的 arm64/x86_64 通用二进制文件缺少部署目标
- sql - 如何在 SQL 中将 JSON 文件拆分为多行
- vue.js - 输入搜索字段后,获取新结果(nuxt,vuex)
- ios - 在 UITableViewCell 中显示和隐藏 UIImageView
- java - 我可以使用@GraphQLQuery 解析模型中没有的字段吗
- php - PHP-FPM:error_reporting() 是否覆盖 php_admin_value[error_reporting]?
- javascript - 用于提交表单的 EventListener 与 JavaScript 中的表单 ID 无关
- flutter - 从抽屉到页面的导航器得到 noSuchMethodError:在 null 上调用了方法 '*'
- sql-server - 如何优化查询,使手动工作可以动态且以优化的方式进行