[英]SQL Joins/Doctrine/Symfony2: Only getting one result from join when I expect multiple
[英]Expect one or no result from a doctrine query builder, what should I use?
我有这个方法:
public function getMonth ($month_name)
{
$q = $this->createQueryBuilder('m');
$q->select('m')
->where('m.name = :name')
->setParameter('name', $month_name);
return $q->getQuery()->getResult();
}
从中我希望找到一个月或0个月。 我在控制器中以这种方式使用此方法:
$month = $em->getRepository('EMExpensesBundle:Month')
->getMonth($this->findMonth());
$month->setSpended($item->getPrice());
我用getSingleResult()
尝试了这个,一切都很完美,直到我发现没有找到月份的情况,一切都失败了!
然后我尝试使用getResult()
,但它返回一个数组然后
$month->setSpended($item->getPrice());
据说被称为非对象并修复它我应该到处使用
$month[0]->setSpended($item->getPrice());
是否有更优雅的方法来实现这一点,而无需在任何地方添加不必要的[0]索引?
另外,在Doctrine 2.1中你可以使用'getOneOrNullResult'
如果你使用getSingleResult
,Doctrine会抛出一个\\Doctrine\\ORM\\NoResultException
,你可以捕获并处理它。 如果你想直接在Repository中捕获它,我会建议:
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();
}
}
别忘了添加一个use Your\\Namespace\\Month;
或者这会失败,因为它找不到Month类!
当然,如果它是一个新实体,你还必须坚持实体。 您可以像这样扩展catch块:
catch(\Doctrine\ORM\NoResultException $e) {
$month = new Month();
$this->_em->perist($month);
return $month;
}
您还可以在控制器中捕获异常,使其更加透明。 但这取决于您的使用案例,最好由您自己解决
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.