2012-10-29 12 views
21

我有這樣的方法:期望一個或沒有從學說查詢生成器的結果,我應該使用什麼?

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]索引?

回答

30

如果您使用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(); 
    } 
} 

不要忘記添加use Your\Namespace\Month;或這將會失敗,因爲它無法找到Month類!

當然你也必須堅持這個實體,以防它是一個新實體。您可以像這樣擴展catch塊:

catch(\Doctrine\ORM\NoResultException $e) { 
    $month = new Month(); 
    $this->_em->perist($month); 

    return $month; 
} 

您也可以在控制器中捕獲異常,使其更加透明。但是,這取決於你的使用情況,並通過自己的最好解決

+0

非常感謝您! :) – Faery

61
+0

你救了我的一天:)。謝謝! –

+0

比在倉庫中嘗試......捕獲更好。應該是問題的答案! –

+4

要小心,如果有多個結果它只是返回一個異常..不是一個空值。 https://coderwall.com/p/prbrlw/doctrine-get-single-row-or-null:no result:return null //多於一個結果:拋出一個NonUniqueResultException異常 – Delphine

相關問題