1

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?

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

6 Comments

I get an [Semantical Error] line 0, col 31 near 'FROM Andrei\StatisticsBundle\Entity\Visit': Error: Class 'FROM' is not defined.
Can you post the output of $qb->getQuery()->getDQL(); ?
"SELECT SUM(v.counter) AS count FROM Andrei\StatisticsBundle\Entity\Visit v GROUP BY v.created_at"
Ah, AS count is wrong, we can't use keywords in the DQL. I edited my answer
Can you edit your response to select multiple values, let's say select also created_at?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.