Stevan Tosic
Stevan Tosic

Reputation: 7199

Doctrine findBy with multiple conditional fields

I have some bad data in the table but not all fields have null values and I want to get all bad rows with one iteration by implementing something like this, if possible.

$contactObj = $this->em->getRepository("ImporterBundle:Contact")
->findBy([$field1 => null OR $field2 => null OR $field3 => null ...]);

Are there is a solution to do something like above example without using repositoryClass?

Upvotes: 2

Views: 8289

Answers (2)

Jannes Botis
Jannes Botis

Reputation: 11242

You can use the matching(Criteria $criteria) function of Doctrine\ORM\EntityRepository:

use Doctrine\Common\Collections\Criteria;

$criteria = Criteria::create()
        ->where(Criteria::expr()->isNull('functions'))
        ->orWhere(Criteria::expr()->isNull('salutation'))
        ->orWhere(Criteria::expr()->isNull('category'))
        ->orWhere(Criteria::expr()->isNull('address'))
        ->orWhere(Criteria::expr()->isNull('city'))
        ->orWhere(Criteria::expr()->isNull('company'));

$contactObj = $this->em->getRepository("ImporterBundle:Contact")
        ->matching($criteria);

Doctrine expression builder

Upvotes: 4

Stevan Tosic
Stevan Tosic

Reputation: 7199

So I just need to use repository class

And use expressions.

public function getBadData() {
    $db = $this->createQueryBuilder('c');

    return $db->select('c')
        ->where($db->expr()->isNull('c.functions'))
        ->orWhere($db->expr()->isNull('c.salutation'))
        ->orWhere($db->expr()->isNull('c.category'))
        ->orWhere($db->expr()->isNull('c.address'))
        ->orWhere($db->expr()->isNull('c.city'))
        ->orWhere($db->expr()->isNull('c.company'))
        ->getQuery()
        ->getResult();
}

As JimL suggested, I had change repository method by using orX()

public function getBadData() {
    $db = $this->createQueryBuilder('c');

    return $db->select('c')
        ->where($db->expr()->orX()->addMultiple(
            [
                'c.functions is null',
                'c.salutation is null',
                'c.category is null',
                'c.address is null',
                'c.city is null',
                'c.company is null'
            ]
        ))
        ->getQuery()
        ->getResult();
}

Which now should be more readable.

Upvotes: 2

Related Questions