I am trying to place a variable into the field name in the query , so I have a schema:
id amazon - tesco - asda - happyshopper -
1 £5 - NULL - NULL - £4.99
2 NULL - £2.99 - NULL - NULL
and then
$store = 'amazon';
$qb = $em->createQueryBuilder();
$products = $qb->select('p')->from('MyBundle:Product', 'p')
->where('p.:store IS NOT NULL')
->setParameter('store', $store)
->add('orderBy', 'p.onSale DESC')
->setMaxResults(40)
->getQuery()
->getResult();
Would return row 1.
What I’ve done for :
->where('p.:store IS NOT NULL')
->setParameter('store', $store)
Is incorrect and it errors.
->where(':store IS NOT NULL')
->setParameter('store', $store)
does not error, but doesn’t apply the store filter.
The short answer here is to just work the store name into the string manually:
or
The long answer is that your database schema could use some work. What happens, for example, if/when you want to add a new store? Are you going to add a new column and re-code the whole thing? The better solution is to separate the concept of “store”, put it in its own table, and join everything together in a different table. Something like this:
Once you configure your tables and your mappings properly, your query turns in to: