Expect one or no result from a doctrine query builder, what should I use?
doctrine-orm, php, symfony
Solution
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:
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!
Of course you must also persist the Entity in case it is a new one. You could extend the catch block to look like this:
catch(\Doctrine\ORM\NoResultException $e) {
$month = new Month();
$this->_em->persist($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
Problem
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: ``` $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! Then I tried with `getResult()`, but it returns an array and then ``` $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?