SELECT * FROM with different values in doctrine2

60 Views Asked by At

So I have little problem, I have code like this:

$query = $repository->createQueryBuilder('p')->
                    where('p.kalorie <= :kalorie AND p.cena <= :kwota AND p.deser = :sniadanie')->
                    setParameters(array(
                        'kalorie' => $kalorie, 
                        'kwota' => $kwota,
                        'sniadanie' => 1))->getQuery(); 
$wynik = $query->getResult();

But I want to do something like:

if id = 1 then 'kwota' => $kwota + 20
if id = 2 then 'kwota' => $kwota + 55
if id = n then 'kwota' => $kwota + x

I mean something like:

SELECT * FROM Recipe WHERE (id = $id AND kwota < ($kwota + 20)) OR (id = $id2 AND kwota < ($kwota + 55)) OR (id = $idN AND kwota < ($kwota + x))
1

There are 1 best solutions below

0
On

If it's about your SQL query, you can use the 'expr' class : http://doctrine-orm.readthedocs.org/en/latest/reference/query-builder.html#the-expr-class

If it's about php variable you can use a ternary operator :

$query = $repository->createQueryBuilder('p')->
                where('p.kalorie <= :kalorie AND p.cena <= :kwota AND p.deser = :sniadanie')->
                setParameters(array(
                    'kalorie' => $kalorie, 
                    'kwota' => $id == 1? $kwota + 20 : ($id == 2 ? $kwota + 55 : $kwota + x),
                    'sniadanie' => 1))->getQuery(); 
$wynik = $query->getResult();