首页 > 解决方案 > 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以便我也可以加载关系。

标签: node.jspostgresqltypeorm

解决方案


您可以通过使用 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)`}
    ]
 });


推荐阅读