How to use andWhere and or Where in the Doctrine?

WHERE a = 1 AND (b = 1 Or b = 2) AND (c = 1 OR c = 2) 

How can I do this in the Doctrine?

 $q->where("a = 1"); $q->andWhere("b = 1") $q->orWhere("b = 2") $q->andWhere("c = 1") $q->orWhere("d = 2") 

this is wrong ... It should be:

 $q->where("a = 1"); $q->andWhere("b = 1") $q->orWhere("b = 2") $q->andWhere("c = 1") $q->orWhere("d = 2") 

but how can i do this? Propel has a getNewCriterion function, and Doctrine ...?

+61
sql php doctrine
Feb 01 '12 at 11:37
source share
4 answers
 $q->where("a = 1") ->andWhere("b = 1 OR b = 2") ->andWhere("c = 2 OR c = 2") ; 
+100
Feb 01 '12 at 11:44
source share

Here is an example for those who have more complex conditions and use Doctrine 2. * with QueryBuilder :

 $qb->where('o.foo = 1') ->andWhere($qb->expr()->orX( $qb->expr()->eq('o.bar', 1), $qb->expr()->eq('o.bar', 2) )) ; 

These are the expressions mentioned in the Czechnology answer.

+64
Dec 28 '15 at 18:45
source share

Why not just

 $q->where("a = 1"); $q->andWhere("b = 1 OR b = 2"); $q->andWhere("c = 1 OR d = 2"); 

EDIT . You can also use the Expr class (Doctrine2).

+11
Feb 01 '12 at 11:45
source share

One thing is missing here: if you have a different number of elements that you want to combine into something like

 WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%') 

and don’t want to build a DQL string yourself, you can use the orX mentioned above, like this:

 $patterns = ['abc', 'def']; $orStatements = $qb->expr()->orX(); foreach ($patterns as $pattern) { $orStatements->add( $qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%')) ); } $qb->andWhere($orStatements); 
+6
Feb 21 '18 at 13:02
source share



All Articles