繁体   English   中英

Doctrine2 LEFT JOIN有两个条件

[英]Doctrine2 LEFT JOIN with 2 conditions

我试图通过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') 

但它总是会返回Photo,即使它处于非活动状态。

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

$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)实体存储库中执行此操作的方法

我相信你的一个人应该是一个或哪个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM