Symfony2 Doctrine Expr 'IS NOT NULL'

65,910

Solution 1

You can use isNotNull:

'query_builder' => function ($er){
    $qb = $er->createQueryBuilder('p');
    $qb
        ->where($qb->expr()->andx(
            $qb->expr()->in('p', '?1'),
            $qb->expr()->isNotNull('p.location')
        ))
        ->setParameter(1, $this->totalScope);
    return $qb;
},

Solution 2

You can also use DQL in your queryBuilder, which is much less ugly IMO.

Quick and dirty example from a controller:

$repo = $this->getDoctrine()->getRepository('AcmeBundle:Transaction');
$query = $repo->createQueryBuilder('t')
    ->where('t.timestamp > :timestamp')
    ->andWhere('t.pinNumber IS NOT NULL')
    ->setParameter('timestamp', new \DateTime('1 day ago'))
    ->getQuery()
;

Easier to read in my estimation.

Share:
65,910
Rixius
Author by

Rixius

I'm a 20 something self-taught Web Developer. I'm an avid polyglot, having learned Ruby, PHP, and Javascript. I'm interested, and teaching myself, Python, Java, C++, Objective-C, and Scheme. I feel that you learn the most about computing, when you explore as many facets as you can, especially it's history. I started my Programming at age 8 writing BASIC Scripts on my VTech Power Pad, a children's "laptop" that was designed for teaching math and grammar.

Updated on November 26, 2020

Comments

  • Rixius
    Rixius almost 2 years

    I'm using the FormType for an Entity of mine, and setting up an entity field. I need two Where clauses in an And, and from what I've read on the Query Builder page, this is at least how I should go about it:

    'query_builder' => function ($er){
        $qb = $er->createQueryBuilder('p');
        $qb
            ->where($qb->expr()->andx(
                $qb->expr()->in('p', '?1'),
                $qb->expr()->not(
                    $qb->expr()->eq('p.location', 'NULL')
                )
            ))
            ->setParameter(1, $this->totalScope)
        ;
        return $qb;
    },
    

    However, the not(eq('col', 'NULL')) doesn't achieve the desired result, and in fact, errors with:

    Error: Expected Literal, got 'NULL'

  • Marcel Burkhard
    Marcel Burkhard about 8 years
    For people that know SQL it might subjectively be less ugly, BUT its also less portable, whereas the expressions-way abstracts the database layer completely away. I personally always use the expressions.
  • keyboardSmasher
    keyboardSmasher almost 8 years
    @MarcelBurkhard The isNotNull method: public function isNotNull($x) { return $x . ' IS NOT NULL'; }
  • keyboardSmasher
    keyboardSmasher almost 8 years
    Furthermore, the IS NOT NULL is DQL not SQL, making it just as portable, but also less ugly. :)
  • Marcel Burkhard
    Marcel Burkhard almost 8 years
    Interesting, so basically there is no advantage for SQL-Aware people of using expressions and I was wasting my time. :(