Doctrine findBy with OR condition

Doctrine OrmFindby

Doctrine Orm Problem Overview


Is it possible to use OR statement in Doctrine findBy() method? I know that given array is interpreted as case1 AND case2... Like this

$this->repos['notif']->findBy(array('status' => 1, 'status' => 2, 'status' => 3);

Stands for

SELECT * FROM `notif` WHERE status=1 AND status=2 AND status=3;

Now I need something to stand for:

SELECT * FROM `notif` WHERE status=1 OR status=2 OR status=3;

Is there a way to get all cases?

Doctrine Orm Solutions


Solution 1 - Doctrine Orm

You can write:

$this->repos['notif']->findBy(array('status' => array(1, 2, 3)));

and that should work too.

Solution 2 - Doctrine Orm

I know that this is old question. Anyways, it's possible to use Criteria for the complex queries (in Doctrine 2 at least):

$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria
  ->orWhere($criteria->expr()->contains('domains', 'a'))
  ->orWhere($criteria->expr()->contains('domains', 'b'));

$groups = $em
  ->getRepository('Group')
  ->matching($criteria);

Solution 3 - Doctrine Orm

As far as I know this is not a supported feature by Doctrine to use IN() queries with findby. You could do two things:

  1. Implement a findByStatus(array $statusTypes) method in your (custom) 'notif' repository class. If you like this approach I can give you a example.

  2. Convert your findBy to the following:

     $qb = $this->repos['notif']->createQueryBuilder('n');
     $data = $qb->where($qb->expr()->in('status', array(1,2,3)))->getQuery()->getResult();
    

That should work either :)

Solution 4 - Doctrine Orm

If you are using MongoDB and need more complex queries, like "less than" linked together with OR, but cannot use a query builder, this also works with this syntax:

   ->findBy(array(
                '$or' => array(
                    array('foo' => array('$lt' => 1234)),
                    array('$and' => array(
                        array('bar' => 45678),
                        array('baz' => array('$lt' => 89013))
                    ))
                )
    ));

Or as a solution for your question:

   ->findBy(array(
                '$or' => array(
                    array('status' => 1),
                    array('status' => 2),
                    array('status' => 3),
                )
    ));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArVanView Question on Stackoverflow
Solution 1 - Doctrine Ormuser3012985View Answer on Stackoverflow
Solution 2 - Doctrine OrmgorodezkiyView Answer on Stackoverflow
Solution 3 - Doctrine OrmKees SchepersView Answer on Stackoverflow
Solution 4 - Doctrine OrmPaul WeberView Answer on Stackoverflow