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

Martin Zeller doctrine, php, zf2 0 Comments

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:

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

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:

// 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();
//

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

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.