Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect one or no result from a doctrine query builder, what should I use?

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?

like image 767
Faery Avatar asked Oct 29 '12 09:10

Faery


1 Answers

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

like image 65
olegkhuss Avatar answered Oct 20 '22 00:10

olegkhuss