2013-10-29 32 views
2
使用自定義DQL功能查詢

我已經添加下面的查詢擴展:在Symfony2中

<?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 [email protected] so I can send you a copy immediately. 
*/ 

namespace MyApp\MainBundle\DQL; 

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

/** 
* "DAY" "(" SimpleArithmeticExpression ")". Modified from DoctrineExtensions\Query\Mysql\Year 
* 
* @category DoctrineExtensions 
* @package  DoctrineExtensions\Query\Mysql 
* @author  Rafael Kassner <[email protected]> 
* @author  Sarjono Mukti Aji <[email protected]> 
* @license  MIT License 
*/ 
class Day extends FunctionNode 
{ 
    public $date; 

    /** 
    * @override 
    */ 
    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) 
    { 
     return "DAY(" . $sqlWalker->walkArithmeticPrimary($this->date) . ")"; 
    } 

    /** 
    * @override 
    */ 
    public function parse(\Doctrine\ORM\Query\Parser $parser) 
    { 
     $parser->match(Lexer::T_IDENTIFIER); 
     $parser->match(Lexer::T_OPEN_PARENTHESIS); 

     $this->date = $parser->ArithmeticPrimary(); 

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

,我想在一組由這樣一個查詢我沒有使用這樣的:

->addGroupBy('DAY(v.created)') 

但它總是給我一個錯誤:

[Semantical Error] line 0, col 90 near 'DAY(v.create': Error: Cannot group by undefined identification or result variable. 

這是爲什麼?

回答

1

你必須在SELECT部分​​如果你想GROUP BY(或ORDER BY)就加的計算值。 使用關鍵字HIDDEN忽略取回結果中的此字段!

$qb 
    // select... 
    ->addSelect('DAY(v.created) AS HIDDEN myGroupByField') 
    // ... 
    ->groupBy('myGroupByField') 
;