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?
Additionally, in Doctrine 2.1 you can use 'getOneOrNullResult'
http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#query-result-formats
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With