Search code examples
phpdoctrine-ormzend-framework2

How to use not equal to filter in Zend


I am very new to Zend.

I know I can use this way to filter my table:

$users = $this->getEntityManager()
         ->getRepository('MyProject\Domain\User')
         ->findBy(array('age' => 20, 'surname' => 'foo'));

This will give me only those users who has age 20 and surname as foo.

However I want to have filter where it gives me user who has age 20 and surname is not foo.

Please advise.


Solution

  • Doctrine does not provide a NOT in their built in find* methods. You have to built your own.

    1. Create custom Repository
    use Doctrine\ORM\EntityRepository; //maybe a slightly different path
    
    class CustomRepo extends EntityRepository
    {
        public function findByAgeNotSurname($age, $surname)
        {
            $qb = $this->createQueryBuilder('u');
    
            return $qb->where('u.age = :age')
                ->andWhere('u.surname != :surname')
                ->setParameters(array('age' => $age, 'surname' => $surname))
                ->getQuery()
                ->getResult();
        }
    }
    
    1. Add Repository to Entity
    /**
     * @ORM\Entity(repositoryClass="Namespace\To\CustomRepo")
     */
    class Entity
    

    Code is not tested but should work.