Friday, November 27, 2015

Passing Array of Conditions To doctrine expr()->orx()

Problem
I needed to construct DQL with a QueryBuilder like this in one of my Symfony project.
[QUERY]... AND WHERE e.type = x OR e.type = Y OR e.type = N [...]
I have list of types in the array but was confused on how to pass the dynamic array to my query builder. List of types will be dynamic.
$qb->andWhere($qb->expr()->orx(CONDITIONS));

Solution:
After some research, I found out about $orX->addMultiple($conditions) method and it fixed my problem.
First I built array of condition using foreach loop and then passed that condition array inside addMultiple method and finally passed orx variable inside addWhere method.
You can build array of condition using foreach like below.
/* $conditions = array('e.type = x', 'e.type = Y', 'e.type = N'); */


foreach($types as $type)
{
   $conditions[] = $qb->expr()->eq('e.type', ':' . $type . '_value');
   $qb->setParameter($type . '_value', $type);
}

 $orX = $qb->expr()->orX();
 $orX->addMultiple($conditions);
 $qb->andWhere($orX);
In this way you can store multiple orx expressions and then add it to andWhere.

Ref: http://stackoverflow.com/a/32250191

No comments:

Post a Comment