首页 > 解决方案 > Symfony - Doctrine - Repository - WHERE 值可能为空或不为空

问题描述

有时 acategory会有一个值,有时它会为 null(省略此条件)。

如果它具有 null ,则以下将不会返回 a 。productcategory

解决此问题的最佳方法是什么,而无需检查是否category为 null 然后使用->where('product.category is null')?我的情况是,我有 30 个不同的字段,有时值会为空,有时则不会。

$this->createQueryBuilder('product')
    ->andWhere('product.category = :category')
    ->setParameter('category', $category)
    ->getQuery()
    ->getOneOrNullResult()
;

标签: phpsymfonydoctrinesymfony4

解决方案


您需要自己添加检查null。您可以通过以下方式执行此操作:

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

if (null === $category) {
  $qb->andWhere('product.category IS NULL');
} else {
  $qb->andWhere('product.category = :category')
    ->setParameter('category', $category)
  ;
}

return $qb->getQuery()
  ->getOneOrNullResult()
;

推荐阅读