Reputation: 1573
How to handle and or in typeorm query builder
Here is a simple query:
SELECT name FROM users WHERE (id = 1 or id = 2) and status = 2
What I tried so far is:
const result = await connection
.getRepository(Users)
.createQueryBuilder("users")
.select(['name'])
.where("id", 1)
.orWhere("id", 2)
.andWhere("status", 2)
.getMany();
The above solution is not providing me a correct record.
Can anyone help me with the correct way?
Upvotes: 0
Views: 105
Reputation: 1106
Your query is evaluating those conditions one by one, rather than executing the OR
and then the AND
against the result of the previous operation. You need to use brackets (import {Brackets} from 'typeorm'
).
const result = await connection
.getRepository(Users)
.createQueryBuilder("users")
.select(['name'])
.where("status", 2)
.andWhere(
new Brackets((qb) => {
qb.orWhere("id", 1);
qb.orWhere("id", 2);
}),
)
.getMany();
Upvotes: 1