0
votes

I'm using Doctrine's QueryBuilder to build a query, and I want to get the count of each value in the table alongside with the value.

this is the SQL query

SELECT choice.choice ,count(*) 
FROM answer 
LEFT JOIN choice ON answer.answer_id_id = choice.id 
WHERE choice.survey_id=1  
GROUP BY choice ;

It returns a table with two columns, the value(choice) and the count

This is the query builder:

class AnswerRepository extends \Doctrine\ORM\EntityRepository
{
    public function getSurveyAnswers($idSurvey)
    {
        $query = $this->createQueryBuilder("a");
        $query
            ->select('COUNT(a.answerId),e.choice')
            ->leftJoin("a.answerId",'e')->addSelect('e.choice')
            ->where('e.Survey = :surv')
            ->setParameter('surv',$idSurvey);

        $kk = $query->getQuery()->getArrayResult();
        dump($kk);
        die();
    }
}

Now, when I run this it returns an array which contains the number of rows and the first value.

1
Could you post your entity model?ste

1 Answers

1
votes

You have no groupby() in your query builder, therefore SQL database returns all rows agregated into a single one.

Try to add grouping to your query builder:

->groupby('e.choice')