diegowc
diegowc

Reputation: 455

Doctrine2 empty parameter on queryBuilder

I am trying to check whether an user email is set or not. I am able to get the ones that are set to NULL but I am missing on the ones that have an empty string as the value. Here is my attempt:

$user = $this->createQueryBuilder('u')
        ->where('(u.email IS NULL OR u.email = :empty)')
        ->setParameter('empty', "''")
        ->getQuery()->getResult()
;

I have no problem getting the NULL emails but I fail to get the empty string emails. Is there any way to accomplish this or is it not supported in DQL?

Upvotes: 0

Views: 2184

Answers (2)

João Alves
João Alves

Reputation: 1941

Worths mention that the Expr Helper from QueryBuilder provides a function for that:

// Example - $qb->expr()->isNull('u.id') => u.id IS NULL
public function isNull($x); // Returns string

So for your case you can do something like:

$qb = $this->createQueryBuilder('u');

$qb
   ->where(
       $qb->expr()->orX(
           $qb->expr()->isNull('u.email'),
           $qb->expr()->eq('u.email', ':empty'),
       )
   )
   ->setParameter('empty', '""');

$users = $qb->getQuery()->getResult();

Upvotes: 0

Alvin Bunk
Alvin Bunk

Reputation: 7764

How about this (EDIT #2):

$user = $this->createQueryBuilder('u')
        ->where('u.email = NULL')
        ->orWhere('u.email = \'\'')
        ->getQuery()->getResult()
;

Does that work?

Upvotes: 1

Related Questions