symfony2:如何在QueryBuilder中使用group_concat

时间:2012-06-01 12:33:29

标签: symfony doctrine-orm

我正在使用名为“Location”的嵌套集(使用Gedmo树)实体。实体“公寓”有location_id以及我需要做什么来将标量值(例如“路径”)映射到返回所有公寓的查询。

在Doctrine1中,我有这段代码:

/**
* Add "path" to each element
* 
* @param Doctrine_Query $query
* @param string $separator
*/
protected function addScalar_path(Doctrine_Query $query, $separator=", ")
{
    $subquery = "k99.root_id=o.root_id AND k99.lft<=o.lft AND k99.rgt>=o.rgt AND k99.level<=o.level" ;

    $query->addSelect("(SELECT GROUP_CONCAT(k99.name ORDER BY k99.level SEPARATOR '$separator') FROM Location k99 WHERE $subquery) AS path") ;
}

注意:“o”别名用于主查询。 这段代码允许我使用

{foreach .... as $appartment}
   {$appartment->path}
...

哪个会打印:

Australia, Victoria, Melbourne, ...other children...

如何在D2中做同样的事情?如何在我的symfony2项目中包含学说扩展?

4 个答案:

答案 0 :(得分:30)

如果要在QueryBuilder中使用它,则必须:

1)添加DQL函数GroupConcat:GroupConcat

2)注册GroupConcat:DQL User Defined Functions

另一种方法是使用NativeQuery:Native SQL


在symfony2中注册一个函数DQL,只需在config.yml中添加GROUP_CONCAT即可:

    entity_managers:
        default:
            dql:
                string_functions:
                    GROUP_CONCAT: YourBundle\Query\Mysql\GroupConcat

有关详细信息,请访问Registering Custom DQL Functions

答案 1 :(得分:16)

如果有任何文章发现,那么现在Github中有一个Doctrine Extensions存储库。回购包含有关如何使用它的说明。您可以使用composer安装它,然后使用您感兴趣的任何功能。

修改

对于用户Tushar的清酒,在Doctrine2的DQL中使用GROUP_CONCAT的方法是简单安装Doctrine Extensions

composer require beberlei/DoctrineExtensions

要启用它:在config.yml中添加以下内容:

doctrine:
 orm:
     dql:
         string_functions:
             group_concat: DoctrineExtensions\Query\Mysql\GroupConcat

然后在您的代码中,您现在应该可以在DQL中使用Group Concat:

$this->createQueryBuilder('location')
            ->select('location')
            ->addSelect("GROUP_CONCAT(DISTINCT location.name SEPARATOR '; ') AS locationNames");

        $result = $queryBuilder->getQuery()->getResult();

或者在原始问题的情况下:

$query->addSelect("(SELECT GROUP_CONCAT(k99.name ORDER BY k99.level SEPARATOR '$separator') FROM Location k99 WHERE $subquery) AS path");

答案 2 :(得分:6)

只是对@ a.aitboudad的答案的补充:
链接的DQL函数GroupConcat似乎具有“对GROUP_CONCAT的有限支持”。
这是完整的支持版本: 配置就像他提到的那样。

// -------------------------------------------------
// Complete support of GROUP_CONCAT in Doctrine2
// -------------------------------------------------
// Original Article: http://habrahabr.ru/post/181666/
// Automated translation to English: http://sysmagazine.com/posts/181666/ 
// Original github commit: https://github.com/denisvmedia/DoctrineExtensions/blob/d1caf21cd7c71cc557e60c26e9bf25323a194dd1/lib/DoctrineExtensions/Query/Mysql/GroupConcat.php

/**
 * DoctrineExtensions Mysql Function Pack
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to kontakt@beberlei.de so I can send you a copy immediately.
 */

namespace DoctrineExtensions\Query\Mysql;

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

/**
 * Full support for:
 *
 * GROUP_CONCAT([DISTINCT] expr [,expr ...]
 *              [ORDER BY {unsigned_integer | col_name | expr}
 *                  [ASC | DESC] [,col_name ...]]
 *              [SEPARATOR str_val])
 *
 */
class GroupConcat extends FunctionNode
{
    public $isDistinct = false;
    public $pathExp = null;
    public $separator = null;
    public $orderBy = null;

    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;
        }

        // first Path Expression is mandatory
        $this->pathExp = array();
        $this->pathExp[] = $parser->SingleValuedPathExpression();

        while ($lexer->isNextToken(Lexer::T_COMMA)) {
            $parser->match(Lexer::T_COMMA);
            $this->pathExp[] = $parser->StringPrimary();
        }

        if ($lexer->isNextToken(Lexer::T_ORDER)) {
            $this->orderBy = $parser->OrderByClause();
        }

        if ($lexer->isNextToken(Lexer::T_IDENTIFIER)) {
            if (strtolower($lexer->lookahead['value']) !== 'separator') {
                $parser->syntaxError('separator');
            }
            $parser->match(Lexer::T_IDENTIFIER);

            $this->separator = $parser->StringPrimary();
        }

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

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

        $fields = array();
        foreach ($this->pathExp as $pathExp) {
            $fields[] = $pathExp->dispatch($sqlWalker);
        }

        $result .= sprintf('%s', implode(', ', $fields));

        if ($this->orderBy) {
            $result .= ' ' . $sqlWalker->walkOrderByClause($this->orderBy);
        }

        if ($this->separator) {
            $result .= ' SEPARATOR ' . $sqlWalker->walkStringPrimary($this->separator);
        }

        $result .= ')';

        return $result;
    }

}

// -------------------------------------------------
// Example of usage:
// -------------------------------------------------
$query = $this->createQueryBuilder('c')
    ->select("
            c as company,
            GroupConcat(b.id, ';', b.headOffice, ';', b.city, ';', s.name
            ORDER by b.id
            SEPARATOR '|') AS branches
        ")->leftJoin('c.branches', 'b')
    ->leftJoin('b.country', 's')
    ->groupBy('c.id')
    ->setFirstResult(0)
    ->setMaxResults(10)
    ->getQuery();
$result = $query->getResult();

答案 3 :(得分:0)

我有类似的问题。 GROUP_CONCAT不允许在里面使用CASE-WHEN。 This library解决了我的问题,也许这会有所帮助。