因为 DAY()
、MONTH()
、YEAR()
和 DATE_FORMAT()
都不是在 Doctrine2 中可用,当使用 PostgreSQL 数据库时,如何在查询生成器中使用这些函数之一?
我找到了几个教程,但它们都适用于 MySQL,没有一个适用于 PostgreSQL。
最佳答案
由于 SQL 语法因数据库供应商而异,因此不可能(或至少不太容易)创建独立于供应商的解决方案。所以这是 PostgreSQL 的一种方法。
我们要使用的 SQL 函数是 to_char()
,参见 https://www.postgresql.org/docs/9.6/static/functions-formatting.html
首先我们需要创建一个自定义 DQL 函数,参见 https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/cookbook/dql-user-defined-functions.html
namespace App\DQL;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\SqlWalker;
class ToChar extends FunctionNode
{
public $timestamp = null;
public $pattern = null;
// This tells Doctrine's Lexer how to parse the expression:
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->timestamp = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_COMMA);
$this->pattern = $parser->ArithmeticPrimary(); // I'm not sure about `ArithmeticPrimary()` but it works. Post a comment, if you know more details!
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
// This tells Doctrine how to create SQL from the expression - namely by (basically) keeping it as is:
public function getSql(SqlWalker $sqlWalker)
{
return 'to_char('.$this->timestamp->dispatch($sqlWalker) . ', ' . $this->pattern->dispatch($sqlWalker) . ')';
}
}
然后我们在 Symfony 4 中注册它,参见 https://symfony.com/doc/current/doctrine/custom_dql_functions.html
# config/packages/doctrine.yaml
doctrine:
orm:
dql:
string_functions:
to_char: App\DQL\ToChar
现在我们可以在任何存储库中使用它:
return $this->createQueryBuilder('a')
->select("to_char(a.timestamp, 'YYYY') AS year")
->groupBy('year')
->orderBy('year', 'ASC')
->getQuery()
->getResult()
;
关于postgresql - Doctrine2 : YEAR, PostgreSQL 的 MONTH、DAY 或 DATE_FORMAT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50890053/