简体   繁体   中英

Postgres date_trunc(text, timestamp) with Doctrine 2 in Symfony?

如何在Symfony中的Doctrine 2中使用Postgres date_trunc(text, timestamp)函数?

  1. In your project, create a new folder named DoctrineExtensions
  2. In the new folder, create a file named DateTrunc.php
  3. Paste this code:

DateTrunc.php

<?php
namespace YOUR_BUNDLE_HERE\DoctrineExtensions;

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

/**
 * DateTrunc ::= "date_trunc" "(" ArithmeticPrimary "," ArithmeticPrimary ")"
 */
class DateTrunc extends FunctionNode
{
  // (1)
  public $firstDateExpression = null;
  public $secondDateExpression = null;

  public function parse(\Doctrine\ORM\Query\Parser $parser)
  {
    $parser->match(Lexer::T_IDENTIFIER); // (2)
    $parser->match(Lexer::T_OPEN_PARENTHESIS); // (3)
    $this->firstDateExpression = $parser->ArithmeticPrimary(); // (4)
    $parser->match(Lexer::T_COMMA); // (5)
    $this->secondDateExpression = $parser->ArithmeticPrimary(); // (6)
    $parser->match(Lexer::T_CLOSE_PARENTHESIS); // (3)
  }

  public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker){
    return 'date_trunc(' .
        $this->firstDateExpression->dispatch($sqlWalker) . ', ' .
        $this->secondDateExpression->dispatch($sqlWalker) .
    ')'; // (7)
  }
}
  1. Add the function to Doctrine configuration

config.yml

orm:
    dql:
        datetime_functions:
             date_trunc: YOUR_BUNDLE_HERE\DoctrineExtensions\DateTrunc

5. You can now use date_trunc(text, timestamp) with Doctrine!

Note: You can easily adapt this code for every additional Postgres/MySQL function. Checkout DoctrineExtensions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM