2013-04-04 136 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