如何按 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 语法错误,字符串结尾".我考虑创建一个自定义函数,但这似乎有点矫枉过正.我对 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屋!