'TypeORM find where conditions AND OR chaining
I'm trying to compose query with Repository find and I don't seem to find a solution for my query. I am aware this is possible with query builder or with Raw() conditions, but I would like to use Repository find if possible.
Where condition I am trying to achieve is field1 = 'string' AND (field2 IS NULL OR field2 >= Date()).
Currently the only solution that works for me is:
where: [
{ param1: 'string', field2: IsNull() },
{ param1: 'string', field2: MoreThenOrEqual(new Date() ) }
]
But this would traslate to (field1 = 'string' AND field2 IS NULL) OR (field1 = 'string' OR field2 >= Date())
I tried something like:
where: [
{ param1: 'string', field2: ( IsNull() || MoreThenOrEqual(new Date() ) ) }
]
But I could make it work. Does anyone know if my original where condition could be done without changing query?
FYI: I'm using Typescript with TypeORM.
Edit 1. Based on request from comments I'm posting my current implementation using queryBuilder (just the where condition):
.where('param1 = :var1', {va1: 'string'})
.andWhere(new Brackets(query => {
query.where('field2 IS NULL')
.orWhere('field3 >= NOW()::DATE')
})
Solution 1:[1]
There is a Brackets in typeorm
Usage:
const sql = await connection
.createQueryBuilder(User, "user")
.where("user.isAdmin = :isAdmin", { isAdmin: true })
.orWhere(
new Brackets((qb) => {
qb.where("user.firstName = :firstName1", {
firstName1: "Hello",
}).andWhere("user.lastName = :lastName1", {
lastName1: "Mars",
})
}),
)
.orWhere(
new Brackets((qb) => {
qb.where("user.firstName = :firstName2", {
firstName2: "Hello",
}).andWhere("user.lastName = :lastName2", {
lastName2: "Earth",
})
}),
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | glinda93 |
