Complex WHERE clauses using the PHP Doctrine ORM
From my experience, each complex where
function is grouped within parenthesis (I'm using Doctrine 1.2.1).
$q->where('name = ?', 'ABC') ->andWhere('category1 = ? OR category2 = ? OR category3 = ?', array('X', 'X', 'X')) ->andWhere('price < ?', 10)
produces the following SQL:
WHERE name = 'ABC' AND (category1 = 'X' OR category2 = 'X' OR category3 = 'X') AND price < 10
The correct way of doing this can be found at doctrine 2 - query builder conditional queries... If statements? as noted by @Jekis. Here is how to use the expression builder to solve this like in @anushr's example.
$qb->where($qb->expr()->eq('name', ':name')) ->andWhere( $qb->expr()->orX( $qb->expr()->eq('category1', ':category1'), $qb->expr()->eq('category2', ':category2'), $qb->expr()->eq('category3', ':category3') ) ->andWhere($qb->expr()->lt('price', ':price') ->setParameter('name', 'ABC') ->setParameter('category1', 'X') ->setParameter('category2', 'X') ->setParameter('category3', 'X') ->setParameter('price', 10);
As it seems like you can't do complex queries using DQL, I wrote the following SQL to pass to the andWhere() method:
$q->andWhere("(category1 IN $subcategory_in_clauseOR category2 IN $subcategory_in_clause OR category3 IN $subcategory_in_clause) AND TRUE");
Note the "AND TRUE", a hack so that the parser wouldn't ignore the outer parentheses.