如何通过DQL中的计算值进行排序 [英] How to order by a computed value in DQL
问题描述
我正在尝试通过查询是否与属性上的原始实体匹配来排序查询结果。我可以在mySQL中轻松地执行以下查询:
I'm trying to order the results of my query by whether or not they match my original entity on a property. I could do this easily in mySQL with the following query:
SELECT * FROM table
ORDER BY prop = 'value' DESC;
但是,在Doctrine中,当我尝试以下操作:
However, in Doctrine, when I attempt the following:
// $qb is an instance of query builder
$qb->select('e')
->from('Entity', 'e')
->orderBy('e.prop = :value', 'DESC')
->setParameter('value', 'value');
// grab values
我得到一个Doctrine语法错误,string of string。我研究创建一个自定义函数,但这似乎是过度的。我是Doctrine的新手,有没有更好的方法呢?
I get a Doctrine syntax error, 'end of string'. I looked into creating a custom function, but that seems like overkill. I'm fairly new to Doctrine, is there a better way to do this?
推荐答案
自从Doctrine ORM 2.2以来,你可以使用 HIDDEN
关键字,并选择其他字段,在本例中为CASE 表达式:
Since Doctrine ORM 2.2, you can use the HIDDEN
keyword and select additional fields, in this case with a CASE expression:
SELECT
e,
CASE WHEN e.prop = :value THEN 1 ELSE 0 END AS HIDDEN sortCondition
FROM
Entity e
ORDER BY
sortCondition DESC
这篇关于如何通过DQL中的计算值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!