我有以下查询,我需要修改它以使用symfony2。
SELECT someColumn, COUNT(*) AS n,
SUM(IF(STATUS = 20,1,0)) AS sent
FROM someTable
WHERE ID = :id;
到目前为止我做了什么:
$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
");
但我得到了可怕的错误:
Error: Expected Literal, got 'CASE'
答案 0 :(得分:0)
假设您从EntityRepository调用它,您可以像这样实例\ Doctrine \ ORM \ QueryBuilder:
$em = $this->_em->createQueryBuilder();
接下来,您可以使用以下命令构建查询:
$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
));
最后你可以像这样检索你的结果:
$qb->getQuery()->getResult();
或者如果您更喜欢普通的旧式数组:
$qb->getQuery()->getArrayResult();
这应该有效,您可以使用以下方法检查生成的查询:
$qb->getQuery()->getDQL(); // get the Doctrine Query Language query
$qb->getQuery()->getSQL(); // get the SQL generated query