Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

symfony - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

config.yml;

  orm:
  dql:
    string_functions:
        GROUP_CONCAT: YourBundleDQLGroupConcat

YourBundleDQLGroupConcat.php;

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

 use DoctrineORMQueryLexer;
 use DoctrineORMQueryASTFunctionsFunctionNode;

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

public function getSql(DoctrineORMQuerySqlWalker $sqlWalker)
{
    return 'GROUP_CONCAT(' .
        ($this->isDistinct ? 'DISTINCT ' : '') .
        $this->expression->dispatch($sqlWalker) .
    ')';
}

public function parse(DoctrineORMQueryParser $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)');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...