php - Symfony - Doctrine - Repository - WHERE 值可能为空或不为空
问题描述
有时 acategory
会有一个值,有时它会为 null(省略此条件)。
如果它具有 null ,则以下将不会返回 a 。product
category
解决此问题的最佳方法是什么,而无需检查是否category
为 null 然后使用->where('product.category is null')
?我的情况是,我有 30 个不同的字段,有时值会为空,有时则不会。
$this->createQueryBuilder('product')
->andWhere('product.category = :category')
->setParameter('category', $category)
->getQuery()
->getOneOrNullResult()
;
解决方案
您需要自己添加检查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()
;
推荐阅读
- angular - Angular + Bootstrap 样式与子组件不同
- angular-material - ng generate @angular/material:material-nav --name=main-nav 不起作用
- javascript - 用 veeValidate VueJS 确认规则:找不到参考?
- git - 如何从错误的 svn 迁移中合并 git 历史记录 - 旧存储库
- python - 在日间映射时旋转时无法排序
- jquery - jqxGrid 内 jqxDropDownList 上的 dropDownVerticalAlignment 顶级问题
- sockets - 离子服务 3
- javascript - 为什么添加引导程序后代码不起作用
- java - JPA 存储库属性表达式
- php - ImageMagick 在转换之前重绘 svg 图像