2013-04-04 133 views
5

我試圖通過ID找到一個'Product',並且在兩個條件左邊加入所有'Photo':語言環境和活動狀態。Doctrine2左加入兩個條件

這裏是我的QueryBuilder:

$queryBuilder = $this->createQueryBuilder('p') 
      ->select('p, photos, photoTranslation') 
      ->leftJoin('p.photos', 'photos') 
      ->leftJoin('photos.translations', 'photoTranslation') 
      ->where('p.id = :id') 
      ->andWhere('(photoTranslation.locale = :locale OR photoTranslation.locale IS NULL)') 
      ->andWhere('(photoTranslation.active = :active OR photoTranslation.active IS NULL)') 
      ->setParameters(array(
       'id' => $id 
       'locale' => $this->getLocale(), 
       'active' => true 
      )); 

它時,有沒有照片或者當有活動的照片能正常工作,而不是在有不活動的照片,因爲它不匹配的一個兩個條件。

如果我只用一個條件,例如僅語言環境的一部分,它工作正常:

$queryBuilder = $this->createQueryBuilder('p') 
      ->select('p, photos, photoTranslation') 
      ->leftJoin('p.photos', 'photos') 
      ->leftJoin('photos.translations', 'photoTranslation') 
      ->where('p.id = :id') 
      ->andWhere('(photoTranslation.locale = :locale OR photoTranslation.locale IS NULL)') 
      ->setParameters(array(
       'id' => $id 
       'locale' => $this->getLocale() 
      )); 

現在,我對論文的結果和取消所有不活動的照片環......但我想在QueryBuilder中做一個乾淨的方法。

我也試圖把左邊的條件JOIN子句:

->leftJoin('photo.translations', 'phototTranslation', Doctrine\ORM\Query\Expr\JOIN::WITH, 'photoTranslation.locale = :locale AND photoTranslation.active = :active') 

但它總是返回照片,即使它是無效的。

回答

0

我相信你andWhere之一應該是一個orWhere

+0

不幸的是,在這種情況下,「活動」和「區域」條件都是必需的。 – Tiois 2013-04-05 11:11:19

+1

@Tiois你可以添加每個表格的小樣本和你所期望的結果嗎?這可能會幫助我和其他人更好地看到潛在問題。 – Shawn 2013-04-05 13:31:46

+0

或在哪裏可以得到WTF結果,強烈建議不要使用它。 – Hornth 2016-09-14 12:32:57

11

對於這個問題的解決方案可能是:

$em = $this->getEntityManager(); 
$qb = $em->createQueryBuilder(); 
$qb 
    ->select('p', 'pp') 
    ->from('Product', 'p') 
    ->leftJoin('p.photos', 'pp') 
    ->leftJoin('pp.translations', 'ppt', Doctrine\ORM\Query\Expr\Join::WITH, $qb->expr()->andX(
     $qb->expr()->eq('ppt.locale', ':locale'), 
     $qb->expr()->eq('ppt.active', ':active') 
    )) 
    ->where('p.id', ':productId') 
    ->setParameters(
     array(
      'productId', $productId, 
      'active', $active, 
      'locale', $locale 
     ) 
    ); 

    $query = $qb->getQuery(); 
    return $query->getResult(); // or ->getSingleResult(); 

注意:這個例子是要做到在Symfony2中(2.3)實體庫的方式

+0

我到處尋找關於如何在連接查詢中添加條件和IN的示例。那'和X'救了我的一天! – 2017-03-03 07:49:04