pass array of conditions to doctrine expr()->orx() method
Asked Answered
W

5

45

I need to construct DQL with a QueryBuilder like this

[QUERY]... AND WHERE e.type = x OR e.type = Y OR e.type = N [...]

I have types in array How can I pass this array to my query builder?

$qb->andWhere($qb->expr()->orx(CONDITIONS));

List of types will be dynamic, calling $qb->andWhere on each foreach types loop will make only more AND WHERE's no more ORs.
Can I store multiply orx expressions and then add it to andWhere? Any idea how to solve this, probably, common problem?

Waldon answered 28/7, 2012 at 20:34 Comment(0)
W
12

I knew that tommarow gonna be a better day. The solution is simple. Your can make array of OR expressions like so

$ors[] = $qb->expr()->orx('e.type = '.$qb->expr()->literal($value));

And then just add it to andWhere()/Where() method of the query builder via join method like so:

$qb->andWhere(join(' OR ', $ors));
Waldon answered 29/7, 2012 at 11:36 Comment(0)
D
88

I hope so, then I found this :

$conditions = array('e.type = x', 'e.type = Y', 'e.type = N');
$orX = $qb->expr()->orX();

foreach ($conditions as $condition) {
    $orX->add($condition);
}

$qb->add('where', $orX);

Using @meze suggestion, you can simplify the code and replace the foreach statement with:

$orX->addMultiple($conditions);
Daily answered 28/7, 2012 at 20:34 Comment(2)
Each day is better than before, foreach can be replaced with $orX->addMultiple($conditions);Pincus
I've change the answer to community wiki. @meze, you're welcome to edit it with your changes.Daily
N
15

@DEY his answer can be simplified. No need for the foreach, this also works:

$conditions = array('e.type = x', 'e.type = Y', 'e.type = N');

$orX = $qb->expr()->orX();
$orX->addMultiple($conditions);

$qb->where($orX);
Nebulous answered 27/8, 2015 at 13:4 Comment(0)
W
12

I knew that tommarow gonna be a better day. The solution is simple. Your can make array of OR expressions like so

$ors[] = $qb->expr()->orx('e.type = '.$qb->expr()->literal($value));

And then just add it to andWhere()/Where() method of the query builder via join method like so:

$qb->andWhere(join(' OR ', $ors));
Waldon answered 29/7, 2012 at 11:36 Comment(0)
T
9

You can also use ... in php like:

$conditions = array('e.type = x', 'e.type = Y', 'e.type = N');
$criteria = Criteria::create();
$criteria->andWhere(Criteria::expr()->orX(...$conditions));
Totalizator answered 26/1, 2018 at 8:55 Comment(0)
A
3

You can also use the call_user_func_array function like this.

It lets you call a method passing an array's items as parameters.

For example:

$conditions = array('e.type = x', 'e.type = Y', 'e.type = N');
$expr = $qb->expr();
call_user_func_array(array($expr, 'orX'), $conditions);
Asylum answered 5/9, 2012 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.