学说2 - 查询构建器,空参数 [英] doctrine2 - querybuilder, empty parameters
本文介绍了学说2 - 查询构建器,空参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果参数没有值怎么办?
what can i do if the parameter has no value?
我的查询:
$query = $this->_em->createQueryBuilder()
->select('u')
->from('Users', 'u')
->where('u.id = ?1')
->andWhere('u.status= ?2')
->setParameter(1, $userid)
->setParameter(2, $status)
->getQuery();
return $query->getResult();
如果没有$status,则不显示任何内容.
if theres no $status, then it doesnt display anything.
我尝试在查询之前放置一个条件来检查它是否为空,但是如果没有设置状态,我可以设置 $status i 的值
i tried putting a condition before the query to check if its null but what value can i set $status iif theres no status set
推荐答案
查询构建器正是用于构建条件查询.你可以这样做:
The query builder is exactly there for building conditional queries. You could do:
$qb = $this->_em->createQueryBuilder();
$query = $qb->select('u')
->from('Users', 'u')
->where('u.id = ?1')
->setParameter(1, $userid);
if ($status) {
$qb->andWhere('u.status = ?2')
->setParameter(2, $status);
}
return $qb->getQuery()->getResult();
附带说明,最佳做法是使用命名占位符 e.G.像这样:
On a side note, it is best practice to use named placeholders e. g. like this:
$qb->andWhere('u.status = :status')
->setParameter('status', $status);
这篇关于学说2 - 查询构建器,空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文