在Doctrine本机查询中使用SQL函数

时间:2013-11-14 09:28:53

标签: symfony orm doctrine

我想在Doctrine本机查询中使用SUM函数,但我一直得到空结果。这是我的代码:

    $em = $this->getDoctrine()->getManager();

    $rsm = new ResultSetMapping();
    $rsm->addEntityResult('AndreiStatisticsBundle:Visit', 'v');
    $rsm->addScalarResult('counter', 'counter');
    $rsm->addScalarResult('created_at', 'created_at');

    $query = $em->createNativeQuery(
        'SELECT SUM(counter) FROM visits GROUP BY created_at', 
        $rsm
    );

很有趣,因为如果我不使用SUM函数,代码将起作用:

    $em = $this->getDoctrine()->getManager();

    $rsm = new ResultSetMapping();
    $rsm->addEntityResult('AndreiStatisticsBundle:Visit', 'v');
    $rsm->addScalarResult('counter', 'counter');
    $rsm->addScalarResult('created_at', 'created_at');

    $query = $em->createNativeQuery(
        'SELECT counter FROM visits GROUP BY created_at', 
        $rsm
    );

有人能说出我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

你能试试吗?

$em = $this->getDoctrine()->getManager();

$repository = $em->getRepository('AndreiStatisticsBundle:Visit');
$qb = $repository->createQueryBuilder('v');
$qb->select('SUM(v.counter) AS counterSum');
$qb->groupBy('v.created_at');

$count = $qb->getQuery()->getSingleScalarResult();