2016-10-01 76 views
0

我有以下學說查詢builer返回我這個錯誤:學說查詢生成器發生故障

No result was found for query although at least one row was expected. 

我懷疑是錯誤出現,因爲它無法找到的協會之一,因爲不是所有的領域都有該關聯。 在哪裏我相信這個問題:

->join('b.answer', 'c') 

的方法:

public function getOneByStep($step, $surveyId) 
    { 
     $qb = $this->getEntityManager()->createQueryBuilder(); 

     return $qb 
      ->select(['u', 'b', 'c']) 
      ->from(QuestionManager::class, 'u') 
      ->join('u.survey', 'a') 
      ->join('u.suggestQuestionManager', 'b') 
      ->join('b.answer', 'c') 
      ->where('u.step = :step') 
      ->andWhere('a.id = :survey') 
      ->setParameter('step', $step) 
      ->setParameter('survey', $surveyId) 
      ->getQuery() 
      ->getSingleResult() 
      ; 
    } 
+0

leftJoin('b.answer','answer')可能想在默認情況下使用左連接進行幾乎任何連接。 – Cerad

+0

你可以發佈它作爲答案,所以我可以接受它嗎? :D –

回答

1

給出的查詢不會在數據庫中的數據返回任何結果。理想情況下應該使用NoResultException進行處理。

use Doctrine\ORM\NoResultException; 

public function getOneByStep($step, $surveyId) 
{ 
    $qb = $this->getEntityManager()->createQueryBuilder(); 
     ->select(['u', 'b', 'c']) 
     ->from(QuestionManager::class, 'u') 
     ->join('u.survey', 'a') 
     ->join('u.suggestQuestionManager', 'b') 
     ->join('b.answer', 'c') 
     ->where('u.step = :step') 
     ->andWhere('a.id = :survey') 
     ->setParameter('step', $step) 
     ->setParameter('survey', $surveyId); 

    try { 
     return $qb->getQuery()->getSingleScalarResult(); 
    } catch (NoResultException $ex) { 
     return; 
    } 
} 
+0

我的問題是該記錄存在於數據庫中。問題在於學說無法找到它,因爲b.answer並不總是會返回記錄。 –

+0

是的,這導致'getSingleResult()'不返回任何導致錯誤的結果。請參閱https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L806和https://github.com/doctrine/doctrine2/blob/c1943624ab1260c629316bab104dc5130c060154/lib/Doctrine/ORM /NoResultException.php#L35 – martin