TovrikTheThird
TovrikTheThird

Reputation: 501

Dynamic wheres using TypeORM

I need to generate a query that looks something like:

SELECT v.* FROM versions v
WHERE 
  (v.id1 = 1 AND v.id2 = 1) OR 
  (v.id1 = 3 AND v.id2 = 2) OR
  (v.id1 = 5 AND v.id2 = 6) OR ...

The parameter to my function contains a list of these paired ids. Unfortunately, id1 and id2 are not the primary keys of this table so I can't use .whereIdsIn().

I am aware of the Brackets object but can't for the life of me figure out how to create a dynamic number of them.

Upvotes: 0

Views: 1978

Answers (1)

Eranga Heshan
Eranga Heshan

Reputation: 5804

Since you put a generic query, I'll try to answer this generally. You can do something like this:

async foo(tupleList: [number, number][]) {
  const builder = createQueryBuilder(Version, 'v');
  for (const tuple of tupleList) {
    builder.orWhere(new Brackets(qb => {
      qb.where("v.id1 = :id1", { id1: tuple[0] })
        .andWhere("v.id2 = :id2", { id2: tuple[1] })
    }));
  }
  const result = await builder.getMany();
}

Upvotes: 2

Related Questions