2012-10-07 90 views
1

在D2.1,QueryBuilder的,我如何使用MySQL的一週功能的一天,我不認爲它提供學說2.1 - DAYOFWEEK函數的替代?

doctrine but isnt there a way i could otherwise? 

$qb->select('p') 
    ->where('YEAR(p.postDate) = :year') 
    ->andWhere('MONTH(p.postDate) = :month') 
    ->andWhere('DAYOFWEEK(p.postDate) = :dayOfWeek'); 

回答

0

這是不可能使用所有的SQL函數與查詢生成器。其中一些是定義的(AVG,SUM等),但大多數不是(包括DAY/WEEK/MONTH)。

您仍然可以編寫本地SQL:

// creating doctrines result set mapping obj. 
$rsm = new Doctrine\ORM\Query\ResultSetMapping(); 

// mapping results to the message entity 
$rsm->addEntityResult('AppBundle\Entity\Post', 'p'); 
$rsm->addFieldResult('p', 'id', 'id'); 
$rsm->addFieldResult('p', 'postDate', 'postDate'); 

$sql = "SELECT id, postDate 
     FROM your_table 
     WHERE YEAR(postDate) = ? 
       AND [...]"; 

$query = $this->_em->createNativeQuery($sql, $rsm); 
$query->setParameter(1, $your_year_here); 
$query->getResult(); 
1

你可以寫一個學說擴展做的工作:

某某\ SomeBundle \ DoctrineExtension \星期幾。 php

class DayOfWeek extends FunctionNode 
{ 
    public $date; 

    /** 
    * @override 
    */ 
    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker) 
    { 
     return "DAYOFWEEK(" . $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); 
    } 
} 

app /配置/ config.yml

doctrine: 
    orm: 
     auto_generate_proxy_classes: "%kernel.debug%" 
     entity_managers: 
      default: 
       naming_strategy: doctrine.orm.naming_strategy.underscore 
       auto_mapping: true 
       dql: 
        datetime_functions: 
         dayofweek: Xyz\SomeBundle\DoctrineExtension\DayOfWeek 

更多詳細覈查這裏:DoctrineExtensions