如何在SQL中使用Group_concat

时间:2014-08-11 10:31:06

标签: symfony doctrine

问题即将面对:

code config.yml

 orm:
    auto_generate_proxy_classes: %kernel.debug%
    auto_mapping: true
    entity_managers:
    default:
     dql:
        string_functions:
                GROUP_CONCAT: bundlename\Query\Mysql\GroupConcat
        string_functions:
            test_string: Acme\HelloBundle\DQL\StringFunction
            second_string: Acme\HelloBundle\DQL\SecondStringFunction
        numeric_functions:
            test_numeric: Acme\HelloBundle\DQL\NumericFunction
        datetime_functions:
            test_datetime: Acme\HelloBundle\DQL\DatetimeFunction

这是我的控制器代码

   $from = 'Entities\Product product';
    $qb->select(" GROUP_CONCAT(product.name) ")
      ->add('from', $from)
      ->innerjoin('Entities\ProductMapping','product_mapping','with','product_mapping.product=product.id' )
      ->where("product_mapping.company in ($company_id) ")
      ->setMaxResults(6)
      ->setFirstResult($i);
     $query = $qb->getQuery();
     $product = $query->getResult();
     print_r($product);

1 个答案:

答案 0 :(得分:1)

您已在string_functions下定义了orm: default: dql:节点两次。第二个将覆盖第一个。

请改为:

 orm:
    auto_generate_proxy_classes: %kernel.debug%
    auto_mapping: true
    entity_managers:
    default:
     dql:
        string_functions:
            test_string: Acme\HelloBundle\DQL\StringFunction
            second_string: Acme\HelloBundle\DQL\SecondStringFunction
            GROUP_CONCAT: bundlename\Query\Mysql\GroupConcat
        numeric_functions:
            test_numeric: Acme\HelloBundle\DQL\NumericFunction
        datetime_functions:
            test_datetime: Acme\HelloBundle\DQL\DatetimeFunction

还要确保添加实际的组concat类。这是我的:

<?php

namespace Tap\Bundle\CoreBundle\Doctrine\Extension\Query;

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

确保编辑名称空间。