Symfony2.3 Doctrine Query Builder复杂查询

时间:2015-03-11 08:44:44

标签: php symfony doctrine-orm doctrine-query

我在Doctrine Query Builder中寻找等效的SQL SELECT语句:

SELECT p.*
FROM position p, fonction f
WHERE ( (p.id = f.position_id) AND (p.type ='MONO_MEMBRE') AND (f.date_fin IS NOT NULL) )
OR ( p.type='MULTI_MEMBRE' )

我试过这种方式:

function(PositionRepository $er) {
    return $er->createQueryBuilder('p')
        ->leftJoin('p.fonctions', 'f', 'WITH', '(f.dateFin IS NOT NULL) AND (p.type= :type_mono)')
        ->orWhere('p.type = :type_multi')
        ->setParameters(array(
            'type_multi' => 'MULTI_MEMBRE',
            'type_mono'  => 'MONO_MEMBRE'
            ));
}

它没有返回预期的结果。有人可以帮我吗?感谢您提前的时间。

2 个答案:

答案 0 :(得分:0)

这应该是等效的。

return $er->createQueryBuilder('p')
    ->leftJoin('p.fonctions', 'f')
    ->where('p.type = :mono')
    ->andWhere('f.date_fin IS NOT NULL')
    ->orWhere('p.type = :muli')
    ->setParameter(['mono' => 'MONO_MEMBRE', 'multi' => 'MULTI_MEMBRE']);

答案 1 :(得分:0)

我按照doctrine documentation on the QueryBuilder找到了解决方案。这是:

function(PositionRepository $er) {
    $qb= $er->createQueryBuilder('p')
            ->leftJoin('p.fonctions', 'f');

    $andModule = $qb->expr()->andX();
    $andModule->add($qb->expr()->isNotNull('f.dateFin'));
    $andModule->add($qb->expr()->eq('p.type', ':mono'));    

    return $qb->where('f IS NULL')
              ->orWhere('p.type = :multi')
              ->orWhere($andModule)
              ->setParameters(array(
                'mono' => 'MONO_MEMBRE',
                'multi' => 'MULTI_MEMBRE'
                ));
}