zuzuleinen
zuzuleinen

Reputation: 2634

Use SQL functions in Doctrine native queries

I want to use the SUM function in a Doctrine native query but I keep getting empty results. Here is my code:

    $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
    );

Is interesting because if I don't use the SUM function the code will work:

    $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
    );

Can someone figures out what am I missing?

Upvotes: 1

Views: 1187

Answers (1)

Pi Wi
Pi Wi

Reputation: 1085

Can you try this?

$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();

Upvotes: 1

Related Questions