How to use andWhere and orWhere in Doctrine? How to use andWhere and orWhere in Doctrine? sql sql

How to use andWhere and orWhere in Doctrine?


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


Here's an example for those who have more complicated conditions and using 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)   ))  ;

Those are expressions mentioned in Czechnology answer.


One thing missing here: if you have a varying number of elements that you want to put together to something like

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

and dont want to assemble 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);