在 Doctrine2 DQL 查询上排序的 CASTING 属性 [英] CASTING attributes for Ordering on a Doctrine2 DQL Query

查看:10
本文介绍了在 Doctrine2 DQL 查询上排序的 CASTING 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 Doctrine2 实体,按他们的 ID 排序,这显然是一个字符串,即使它只包含数字.所以我想做的是这样的:

I am trying to get Doctrine2 Entities, ordered by their ID which apparently is a String even though it contains only Numbers. So what I would like to do is something like this:

SELECT entity1, cast (entity1.id AS integer) AS orderId
FROM NamespaceBlaMyEntity 
ORDER BY orderId

有没有办法在 Doctrine2 中做这样的事情?或者,如果我无法更改 id 的类型(当然是由于客户要求),那么获得我的结果的最佳做法是什么?

Is there a way to do something like this in Doctrine2? Or, what would be the best practise to get my Result if i can't change the type of the id (due to customer requirements of course)?

注意:我不是在问 SQL 代码,我是在问一个 Doctrine2 解决方案,最好是在 DQL 中

Attention: I am not asking SQL Code, i am asking for a Doctrine2 Solution, preferably in DQL

推荐答案

你应该可以 添加你自己的函数来实现这个功能.

You should be able to add your own function to implement this feature.

这个类看起来像这样:

namespace MyProjectQuery;

use DoctrineORMQueryASTFunctionsFunctionNode;
use DoctrineORMQueryLexer;
use DoctrineORMQueryParser;
use DoctrineORMQuerySqlWalker;

class CastAsInteger extends FunctionNode
{
    public $stringPrimary;

    public function getSql(SqlWalker $sqlWalker)
    {
        return 'CAST(' . $this->stringPrimary->dispatch($sqlWalker) . ' AS integer)';
    }

    public function parse(Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);

        $this->stringPrimary = $parser->StringPrimary();

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

你需要注册你的函数:

$config = $em->getConfiguration();
$config->addCustomNumericFunction('INT', CastAsInteger::class);

然后就可以使用了:

SELECT e, INT(e.id) AS HIDDEN orderId
FROM NamespaceBlaMyEntity e
ORDER BY orderId

PS:通过添加 HIDDEN 关键字,别名 orderId 将不会出现在结果中(并且仅用于排序).

PS: By adding the HIDDEN keyword, the alias orderId won't be in the results (and is only used for ordering).

这篇关于在 Doctrine2 DQL 查询上排序的 CASTING 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆