Multiple conditional count in one to many data fetching with Doctrine ORM

22 Views Asked by At

I got the following situation: I have a Parent entity, which has many Child entities. The Child entity has a property named 'Score'. What I aim is to fetch the Parent entities with the following data selected:

  • countScoreOne -> return the number of rows from the Child entity's table where the Score is 1
  • countScoreTwo -> return the number of rows from the Child entity's table where the Score is 2
  • countScoreThree -> return the number of rows from the Child entity's table where the Score is 3

After looking around, the following query was mainly suggested:

$qb = $this->createQueryBuilder('p')
        ->select('p')
        ->innerJoin('p.children', 'c')
        ->addSelect('SUM(case when c.score=1 then 1 else 0 end) AS countScoreOne')
        ->addSelect('SUM(case when c.score=2 then 1 else 0 end) AS countScoreTwo')
        ->addSelect('SUM(case when c.score=3 then 1 else 0 end) AS countScoreThree');

$qb->groupBy('p.id');

return $qb->getQuery()->getArrayResult()

The problem with this query is that it gives completely wrong figures. In some cases the parent has not children with score 1, yet the query returns 9 . Any suggestion with a different approach is also welcomed. I've been looking for a couple hours for a solution, and this seemed to be the best so far.

If I simply count the c alias, that gives the right number. Thanks.

UPDATE

I managed to find the source of the problem. I had to wrap each parameter value into a pair of quotes. So it looks like this:

$qb = $this->createQueryBuilder('p')
        ->select('p')
        ->innerJoin('p.children', 'c')
        ->addSelect('SUM(case when c.score=\'1\' then 1 else 0 end) AS countScoreOne')
        ->addSelect('SUM(case when c.score=\'2\' then 1 else 0 end) AS countScoreTwo')
        ->addSelect('SUM(case when c.score=\'3\' then 1 else 0 end) AS countScoreThree');

$qb->groupBy('p.id');

return $qb->getQuery()->getArrayResult();

So recomposing my question, it's more MySql related, rather than Doctrine ORM. If the column is type (and the entity's property as well) integer, then why do I need to pass it to the query as a string? My MySql knowledge is not the strongest. Thanks.

0

There are 0 best solutions below