I have the following query which I need to modify to work with symfony2.
SELECT someColumn, COUNT(*) AS n,
SUM(IF(STATUS = 20,1,0)) AS sent
FROM someTable
WHERE ID = :id;
What I have done till now:
$query = ("SELECT myEntity.someField AS someColumn,
SUM(CASE WHEN myEntity.status = '20' then 1 ELSE 0 END) as sent
FROM AppRoot\MyBundle\Entity\MyEntity myEntity
WHERE myEntity.id = :id
");
But I get the dreaded error:
Error: Expected Literal, got 'CASE'
Assuming you call it from an EntityRepository, you can instance a \\Doctrine\\ORM\\QueryBuilder like this:
$em = $this->_em->createQueryBuilder();
Next, you can build the query using:
$qb->select(array(
'myEntity.someField as someColumn',
'count(myEntity) as n',
'SUM(CASE WHEN myEntity.status = :status then 1 ELSE 0 END) as sent',
... // add all the columns you need
))
->from('AppRoot\MyBundle\Entity\MyEntity','MyEntity')
->where( $qb->expr()->eq('myEntity.id', ':id') )
->setParameters(array(
'status'=>'20',
'id' => $theEntityId
));
And finally you can retrieve your result like this:
$qb->getQuery()->getResult();
or if you prefer a plain old-style array:
$qb->getQuery()->getArrayResult();
This should work and you may inspect the generated queries with:
$qb->getQuery()->getDQL(); // get the Doctrine Query Language query
$qb->getQuery()->getSQL(); // get the SQL generated query
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.