Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2: Using group_concat in QueryBuilder(Doctrine)

I am trying to use GROUP_CONCAT() in doctrine using querybuilder()

I tried this

   $qb=$this->em->createQueryBuilder();
   $qb->select('category.id industry_id,category.name industry_name,group_concat(category.name)')

but its not working this way.

I also refered symfony2: how to use group_concat in QueryBuilder

but all the link provided by #a.aitboudad are going 404. can anyone give me link or something to do it ?

thanks

like image 554
Sunil Kumar Avatar asked Jul 14 '15 08:07

Sunil Kumar


1 Answers

You will need to create your own Doctrine function to use GROUP_CONCAT;

config.yml;

  orm:
  dql:
    string_functions:
        GROUP_CONCAT: Your\Bundle\DQL\GroupConcat

Your\Bundle\DQL\GroupConcat.php;

(source: https://github.com/beberlei/DoctrineExtensions/blob/master/src/Query/Mysql/GroupConcat.php)

 use Doctrine\ORM\Query\Lexer;
 use Doctrine\ORM\Query\AST\Functions\FunctionNode;

 class GroupConcat extends FunctionNode
 {
public $isDistinct = false;
public $expression = null;

public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
    return 'GROUP_CONCAT(' .
        ($this->isDistinct ? 'DISTINCT ' : '') .
        $this->expression->dispatch($sqlWalker) .
    ')';
}

public function parse(\Doctrine\ORM\Query\Parser $parser)
{

    $parser->match(Lexer::T_IDENTIFIER);
    $parser->match(Lexer::T_OPEN_PARENTHESIS);

    $lexer = $parser->getLexer();
    if ($lexer->isNextToken(Lexer::T_DISTINCT)) {
        $parser->match(Lexer::T_DISTINCT);

        $this->isDistinct = true;
    }

    $this->expression = $parser->SingleValuedPathExpression();

    $parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}

Then in your query builder (or DQL);

  $qb->select('GROUP_CONCAT(category.name)');
like image 191
Steve_B19 Avatar answered Sep 20 '22 11:09

Steve_B19