postgresql - Doctrine2 : YEAR, PostgreSQL 的 MONTH、DAY 或 DATE_FORMAT

标签 postgresql doctrine-orm symfony4

因为 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/

相关文章:

sql - 使用 ID 加入的 Rails 3 Active Record 查询接口(interface)的问题

sql - 使用来自自身的值更新 PostgreSQL 表

dependency-injection - 通过 services.yml 将自定义实体存储库类传递给服务

symfony - 学说2映射覆盖从MappedSuperclass继承的inversedBy字段

php - 在 symfony 上构建表单,属性不存在

symfony - 如何在Symfony中获得Redis队列中未处理的消息数

sql - 从 PostgreSQL 中的 unix 时间中提取年份

postgresql - 元数据库/Clojure 错误 : Unfreezable type: class org. postgresql.jdbc.PgArray

php - Symfony/Doctrine 2 ManyToOne关系,ORM不保留列的设置值,发生错误

symfony - Symfony 4 中的私有(private)、自定义 bundle 在哪里?