【问题标题】:TypeORM : Generate query with nested AND and ORTypeORM : 使用嵌套的 AND 和 OR 生成查询
【发布时间】:2020-10-03 21:44:20
【问题描述】:

我正在使用 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 来加载关系。

【问题讨论】:

  • 您可以将status: 1 添加到第二个 where 查询中,它应该可以工作
  • 实际上,我正在动态生成上述内容,其中可能有任意数量的条件。

标签: node.js postgresql typeorm


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多