2012-03-22 21 views
11

Devo aggiungere dinamicamente espressioni OR al generatore di query restituito da getListQueryBuilder, subito dopo l'aggiunta di una clausola where. Non riesco a trovare un modo adeguato per farlo, ho appena iniziato a imparare Doctrine.Concatenamento orX in Doctrine2 query builder

Come posso "concatenare" un determinato numero di orX e aggiungerli al mio builder?

public function getListQueryBuilder($ownerId) 
{ 
    $qb = $this->createQueryBuilder('t'); 

    return $qb 
     ->where($qb->expr()->eq('t.user', ':user')) 
     ->setParameter('user', $ownerId); 
} 

$builder = getListQueryBuilder(4); 

// $ORs is a dynamically builded array, here is just an example 
$ORs = array(); 
$ORs[] = $builder->expr()->like("t.name", 'my name'); 
$ORs[] = $builder->expr()->like("t.description", 'desc'); 

// Adding ORs to the builder 
$builder->andWhere($builder->expr()->orX(/* here */)); 

risposta

20

È possibile controllare this solution:

$orX = $builder->expr()->orX(); 
foreach($ORs as $or) { 
    $orX->add($or); 
} 
$builder->andWhere($orX); 
+7

Se non volete leggere l'articolo completo: $ ORX = $ builder-> expr() -> Orx(); foreach ($ ORs come $ o) { $ orX-> aggiungi ($ o); } $ builder-> andWhere ($ orX); –

+1

@LouTerrailloune che dovrebbe diventare parte della risposta –

+0

Questo ha fatto il trucco per me! evviva per indicarlo :) – Sharpy35

8

mi sono imbattuto sullo stesso problema e provato:

$builder->andWhere($builder->expr()->orX($ORs)); 

ma non funziona in quanto ORX chiama "ritorno nuova Expr \ Orx (func_get_args());" internamente e si finisce con qualcosa come array (array (OR1, OR2))

aver guardato l'API però ho capito che si può fare questo:

$builder->andWhere($builder->expr()->orX()->addMultiple($ORs)); 

o non utilizzare $ tavolo OR affatto solo problema:

$orx = $builder->expr()->orX(); 
$orx->add($builder->expr()->like("t.name", 'my name')); 
$orx->add($builder->expr()->like("t.description", 'desc')); 
$builder->andWhere($orx); 
Problemi correlati