zf2, doctrine module and expressions (like ‘IS NOT NULL’)

Martin Zellerdoctrine, php, zf2 Leave a Comment

Currently I am working on a migration of a zend framework 1 project to zf2 (zend framework 2). Furthermore I want to introduce Doctrine to the project. There are some useful articles about installing and using the zf2 doctrine module. After some hours I found out how to use modules and Doctrine in zf2.
Sometimes you will have code like this:

[php] // em: \Doctrine\ORM\EntityManager
$result = $this->em->getRepository(‘\YourNameSpace\Model\ModelObject’)->findBy(array(‘column1’=>’xyz’), array(‘orderBy’=>’asc’));
//[/php]

You can find all this stuff with google, BUT what is hard to find out: how to use expressions (like ‘IS NOT NULL’) with Doctrine with the zf2 doctrine module.
What if you want to add to our previous statement “and column2 is not null”?
See the solution:

[php] // em: \Doctrine\ORM\EntityManager
$qb = $this->em->getRepository(‘\YourNameSpace\Model\ModelObject’)->createQueryBuilder(‘c’);
// add first where clause
$qb->where($qb->expr()->eq(‘c.column1′,’:ccol1′));
// add the second where clause with our "IS NOT NULL" expression
$qb->andWhere($qb->expr()->isNotNull(‘c.column2’));
// set the parameters
$qb->setParameter(‘ccol1’, ‘xyz’);
// get the query
$query = $qb->getQuery();
// fetch the result
$result = $query->getResult();
//
[/php]

For the other expressions look into the class Doctrine\ORM\Query\Expr .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.