1

我想在 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
    );

有人能弄清楚我错过了什么吗?

4

1 回答 1

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();
于 2013-11-14T10:04:19.747 回答