【问题标题】:Doctrine2 LEFT JOIN with 2 conditionsDoctrine2 LEFT JOIN 有 2 个条件
【发布时间】:2023-04-06 18:19:01
【问题描述】:

我正在尝试通过 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')

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

【问题讨论】:

    标签: mysql doctrine-orm symfony-2.0


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

    【讨论】:

    • 我到处寻找有关如何在连接查询中添加条件和 IN 的示例。 'andX' 拯救了我的一天!
    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 2012-08-22
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多