Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM "OR" "AND "operator combination

I'm not sure how to use the OR condition in typeOrm where clause, could not find solution so far.

I have a db call as follows

db.getRepository(MyModel).find({
where:{
  type : "new",
  status: "A"
  region: "central"
  zip_code: "4831"
  }
  })

I need to modify the above call same as to below SQL query

select * from model where type="new" and status="A" and (region="central" or zip_code="4831");
like image 535
Abhilash Shajan Avatar asked Mar 31 '26 14:03

Abhilash Shajan


2 Answers

You can use query builder for that but if the goal is to use only the find operation you can do the following

db.getRepository(MyModel).find({
  where: [
    {
      type : "new",
      status: "A",
      region: "central"
    },
    {
      type : "new",
      status: "A",
      zip_code: "4831"
    },
  ]
})

When you provide the list of where conditions it is considered as OR operation.

Although the end result is the same, this won't produce the exact query you desire. It would be

select * from model 
  where 
    (type="new" and status="A" and region="central")
  OR  
    (type="new" and status="A" and zip_code="4831")

like image 84
n1md7 Avatar answered Apr 02 '26 03:04

n1md7


You can use the createQueryBuilder of typeorm. You can check the use of bracket here. You can use orWhere wherever you need to use the OR condition. By your query, you can use the below code:

createQueryBuilder("MyModel")
  .where("MyModel.type = :type", { type: "new" })
  .andWhere("MyModel.status = :status", { status: "A" })
  .andWhere(
    new Brackets((qb) => {
      qb.where("MyModel.region = :region", {
        region: "central",
      }).orWhere("MyModel.zip_code = :zip", { zip: "4831" });
    })
  );

This will result in the SQL query:

select * from model where type="new" and status="A" and (region="central" or zip_code="4831");
like image 40
Ritik Banger Avatar answered Apr 02 '26 03:04

Ritik Banger