Search code examples
phpdoctrine-orm

How to query NOT NULL with Doctrine 2?


I have exactly the same question as asked before, but the last question is 6 years old and new Doctrine versions exist, so I am now asking this in reference to the latest version of Doctrine.

I have table Test:

Test:

id | name 
1  | aaa
2  | 
3  | ccc
4  | aaa
5  | 
6  | ddd

I want result where name is NOT NULL:

aaa
ccc
aaa
ddd

This syntax doesn't work:

$em->getRepository('Test')->findBy(array('name' => notnull));

Is there something similar that will work using the findBy syntax?


Solution

  • There is no shortcut method like findBy, but you can use the query builder:

    $qb = $em->createQueryBuilder(); // $em is your entity manager
    $result = $qb->select("t")
        ->from("Test t")
        ->where($qb->expr()->isNotNull("t.name"))
        ->getQuery()->getResult();
    

    This will give you all entities where name is not NULL.

    See http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html for a reference of all query builder methods, including the ones accessible through $qb->expr().