php 期望来自学说查询构建器的一个结果或没有结果,我应该使用什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13119032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Expect one or no result from a doctrine query builder, what should I use?
提问by Faery
I have this method:
我有这个方法:
public function getMonth ($month_name)
{
$q = $this->createQueryBuilder('m');
$q->select('m')
->where('m.name = :name')
->setParameter('name', $month_name);
return $q->getQuery()->getResult();
}
From it I expect to find one month or 0 months. I use this method in this way in my Controllers:
我希望从中找到 1 个月或 0 个月。我在我的控制器中以这种方式使用这种方法:
$month = $em->getRepository('EMExpensesBundle:Month')
->getMonth($this->findMonth());
$month->setSpended($item->getPrice());
I tried this with getSingleResult()and everything was perfect untill I came across a case when no month was found and everything failed really bad!
我试过这个,getSingleResult()一切都很完美,直到我遇到一个没有找到月份的情况,一切都非常糟糕!
Then I tried with getResult(), but it returns an array and then
然后我尝试使用getResult(),但它返回一个数组,然后
$month->setSpended($item->getPrice());
is said to be called on a non-object and to fix it I should use everywhere
据说在非对象上调用并修复它我应该在任何地方使用
$month[0]->setSpended($item->getPrice());
Is there a more elegant way to achieve this without the need to add unnecesary [0] index everywhere?
有没有更优雅的方法来实现这一点,而无需在任何地方添加不必要的 [0] 索引?
回答by olegkhuss
Additionally, in Doctrine 2.1 you can use 'getOneOrNullResult'
此外,在 Doctrine 2.1 中,您可以使用“getOneOrNullResult”
回答by Sgoettschkes
If you use getSingleResult, Doctrine throws a \Doctrine\ORM\NoResultException, which you can catch and handle it. If you want to catch this directly in the Repository, I would suggest:
如果您使用getSingleResult,Doctrine 会抛出一个\Doctrine\ORM\NoResultException,您可以捕获并处理它。如果您想直接在存储库中捕获它,我建议:
public function getMonth ($month_name)
{
$q = $this->createQueryBuilder('m');
$q->select('m')
->where('m.name = :name')
->setParameter('name', $month_name);
try {
return $q->getQuery()->getResult();
}
catch(\Doctrine\ORM\NoResultException $e) {
return new Month();
}
}
Dont forget to add a use Your\Namespace\Month;or this will fail because it cannot find the Month class!
不要忘记添加 ause Your\Namespace\Month;否则会失败,因为它找不到 Month 类!
Of course you must also persist the Entity in case it is a new one. You could extend the catch block like this:
当然,您还必须保留实体,以防它是新实体。您可以像这样扩展 catch 块:
catch(\Doctrine\ORM\NoResultException $e) {
$month = new Month();
$this->_em->perist($month);
return $month;
}
You could also catch the exception in your controller, making it more transparent. But this depends on your use cases and is best solved by yourself
您还可以在控制器中捕获异常,使其更加透明。但这取决于您的用例,最好由您自己解决

