Ashutosh
Ashutosh

Reputation: 4675

TypeORM : Generate query with nested AND and OR

I am using NodeJS + TypeORM + PostgreSQL

I find it difficult to generate queries based on my requirements.

I need to generate the following query:

select * from clinics where status = 1 and (last_sync_date < x or last_sync_date is null)

Here x is current date - 10 days.

I tried the following query:

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() }
  ]
});

But the result is this:

select * from clinics where (status = 1 and last_sync_date < x) or last_sync_date is null;

What do I need to change in the code above?

I want to use find so that I can load relations as well.

Upvotes: 1

Views: 472

Answers (1)

noam steiner
noam steiner

Reputation: 4444

You can solve this by creating the query with js conditions and then assign it to the FindConditions.

For example:

 const whereCondition = testResultId ?
            {patientId, id: Not(testResultId), clinicId} :
            {patientId, clinicId}

 const tr = await TestResult.findOne({
            where: whereCondition,
        })

Or you can use Raw operator:


 let clinics= await clinicRepo.find({
    where : [
        {status: 1,
         last_sync_date: Raw(alias => `(${alias} < ${now} OR ${alias} IS NULL)`}
    ]
 });

Upvotes: 1

Related Questions