Home > other >  TypeORM "OR" "AND "operator combination
TypeORM "OR" "AND "operator combination

Time:09-03

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");

CodePudding user response:

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");

CodePudding user response:

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")

  • Related