2013-07-22 26 views
12

我在我的要求下Symfony2的原則拋NonUniqueResultException

public function getLastViewUpdate($view) 
{ 
    $qb = $this->getEntityManager()->createQueryBuilder(); 

    $result = $qb->select('vu') 
     ->from('EasyApp\ApplicationBundle\Entity\ViewUpdate', 'vu') 
     ->where('vu.view = :view') 
     ->orderBy('vu.date','DESC') 
     ->setParameter('view', $view) 
     ->getQuery() 
     ->getSingleResult(); 

    return $result; 
} 

扔NonUniqueResultException一個問題,但我不真的知道爲什麼,我有可能進口的東西,但我找不到

CRITICAL - Uncaught PHP Exception Doctrine\ORM\NonUniqueResultException: "" at /Users/antoine/Documents/projects/easyApp/application/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php line 621 

感謝您的幫助

回答

32

您可以檢查getSingleResult功能

/** 
* Gets the single result of the query. 
* 
* Enforces the presence as well as the uniqueness of the result. 
* 
* If the result is not unique, a NonUniqueResultException is thrown. 
* If there is no result, a NoResultException is thrown. 
* 
* @param integer $hydrationMode 
* @return mixed 
* @throws NonUniqueResultException If the query result is not unique. 
* @throws NoResultException If the query returned no result. 
*/ 
public function getSingleResult($hydrationMode = null) 
{ 
    ... 
    if (count($result) > 1) { 
     throw new NonUniqueResultException; 
    } 
    ... 
} 

的聲明爲了解決這個問題,您可以設置LIMIT查詢和與->setMaxResults(1)得到只有一個結果。

+0

由於它的工作原理,但此是不是很合適,我不明白爲什麼拋出一個錯誤創建一個嚴重錯誤 – Ajouve

+1

它不是一個錯誤,它的例外。檢查'getSingleResult'代碼,我更新了我的答案。 –

+0

好的,但我的頁面沒有取,我在symfony有一個500錯誤 – Ajouve

1

這只是意味着您有兩個或多個ViewUpdates具有相同的視圖。

6

如果您期望得到1個以上的結果,請不要使用getSingleResult ...使用此函數會執行結果的唯一性檢查,這是此函數的目的。

很多選擇:

  • 使用getSingleResult與例外處理(如try {...} catch (NonUniuqueResultException $e) {...}或調整你的數據庫結構,以避免重複,
  • 使用getSingleResult,並添加setMaxResults(1),但是這是真的相信一個奇怪的方式您的數據庫模型,
  • 使用getResult並做返回的結果的東西。
+1

謝謝你的回答 – Ajouve