-->

Doctrine2 LEFT JOIN带2分的条件(Doctrine2 LEFT JOIN with

2019-08-19 13:26发布

我试图通过ID找到一个“产品”,和左连接所有它的两个条件“照片”:区域设置和活动状态。

这里是我的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的做。

我也试图把条件对LEFT JOIN子句:

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

但它总是返回照片,即使它是无效的。

Answer 1:

对于这个问题的解决方案可能是:

$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)实体库的方式



Answer 2:

我相信你andWhere之一应该是一个orWhere



文章来源: Doctrine2 LEFT JOIN with 2 conditions