queryBuilder 上的 Doctrine2 空参数
Doctrine2 empty parameter on queryBuilder
我正在尝试检查是否设置了用户电子邮件。我能够获得设置为 NULL 的那些,但我缺少那些具有空字符串作为值的那些。这是我的尝试:
$user = $this->createQueryBuilder('u')
->where('(u.email IS NULL OR u.email = :empty)')
->setParameter('empty', "''")
->getQuery()->getResult()
;
我可以毫无问题地获取 NULL 电子邮件,但我无法获取空字符串电子邮件。有什么办法可以做到这一点还是 DQL 不支持它?
这个怎么样(编辑#2):
$user = $this->createQueryBuilder('u')
->where('u.email = NULL')
->orWhere('u.email = \'\'')
->getQuery()->getResult()
;
这样行吗?
值得一提的是 Expr Helper from QueryBuilder 提供了一个功能:
// Example - $qb->expr()->isNull('u.id') => u.id IS NULL
public function isNull($x); // Returns string
因此,对于您的情况,您可以执行以下操作:
$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();
我正在尝试检查是否设置了用户电子邮件。我能够获得设置为 NULL 的那些,但我缺少那些具有空字符串作为值的那些。这是我的尝试:
$user = $this->createQueryBuilder('u')
->where('(u.email IS NULL OR u.email = :empty)')
->setParameter('empty', "''")
->getQuery()->getResult()
;
我可以毫无问题地获取 NULL 电子邮件,但我无法获取空字符串电子邮件。有什么办法可以做到这一点还是 DQL 不支持它?
这个怎么样(编辑#2):
$user = $this->createQueryBuilder('u')
->where('u.email = NULL')
->orWhere('u.email = \'\'')
->getQuery()->getResult()
;
这样行吗?
值得一提的是 Expr Helper from QueryBuilder 提供了一个功能:
// Example - $qb->expr()->isNull('u.id') => u.id IS NULL
public function isNull($x); // Returns string
因此,对于您的情况,您可以执行以下操作:
$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();