Search code examples
doctrinedoctrine-query

How to change the selected name of a doctrine querybuilder expression inside of a select


I am trying to change the returned array from a doctrine query from:

['city' => 'Warsaw', '1' => '2']

to:

['city' => 'Warsaw', 'count' => '2']

My query looks like this:

$queryBuilder = $this->createQueryBuilder('geo');
$queryBuilder->select([
    'geo.city',
    $queryBuilder->expr()->countDistinct('geo.id')
]);
$queryBuilder->groupBy('geo.city');
$result = $queryBuilder->getQuery()->getResult();

Not sure how to correctly write a AS count into this subexpression.


Solution

  • The Expr class is nothing more than a set of helpers to write your expressions. Nothing prevents you from combining it with strings:

    // $qb your query builder
    $qb->addSelect($qb->expr()->countDistinct('geo.id') . ' AS geo_count');
    

    If you don't like mixing expr and strings, you could even write the DQL directly:

    $qb->addSelect('COUNT(DISTINCT geo.id) AS geo_count');
    

    Note: I used geo_count as the alias since you can't use count as it will be interpreted as the COUNT function by the DQL parser.