Doctrine2 复杂排序
我有一个评论表,每个评论都有一个状态,如“已批准”、“等待审核”、“隐藏”。当我显示评论时,我希望它们根据状态进行排序 - “已批准”,然后“等待审核”,然后“隐藏”。我可以使用 UNION 来做到这一点,但这在性能方面是一个糟糕的解决方案。
我想知道 Doctrine2 是否有相当于“ORDER BY (status <> 'hidden') DESC”的东西?我知道按计算字段排序( Doctrine2 @OrderBy 可以计算字段吗? )但我不知道如何在这里应用它。
I've got a comments table, and each comment has a status like "approved", "awaiting moderation", "hidden". When I show the comments I want them to be sorted according to their statuses - "approved", then "awaiting moderation", then "hidden". I can do that with UNIONs but that's a poor solution performance-wise.
I wonder if there's a Doctrine2 equivalent for "ORDER BY (status <> 'hidden') DESC"? I know about ordering by calculated fields ( Can Doctrine2 @OrderBy a calculated field?) but I don't see how to apply it here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 2.2,则有一个
CASE
表达式和一个HIDDEN
关键字:从 Doctrine CaseExpression EBNF,可以使用
SELECT
c、
CASE WHEN (c.status = 'hidden') THEN 1 ELSE 0 END AS HIDDEN sortValue
从
评论c
订购依据
排序值降序
There is a
CASE
expression and aHIDDEN
keyword if you're using 2.2:As of Doctrine CaseExpression EBNF, you can use
SELECT
c,
CASE WHEN (c.status = 'hidden') THEN 1 ELSE 0 END AS HIDDEN sortValue
FROM
Comment c
ORDER BY
sortValue DESC
您解决这个问题了吗?另一种方法是执行 sql 查询,在其中为状态赋予值,并根据需要进行排序。
$conn = $entity_manager->getConnection();
$stmt = $conn->查询("
选择
d.*,案例状态为“已批准”,然后为 1
当“等待审核”时,则 2
当“隐藏”时,则 3 结束序列
从表中按顺序排列
");
只是循环抛出它们。
Did you resolve this issue? Another way you can do it, is do an sql query by where you give values to the status, and order by that if you want.
$conn = $entity_manager->getConnection();
$stmt = $conn->query("
select
d.*, case status when 'approved' then 1
when 'awaiting moderation' then 2
when 'hidden' then 3 end sequence
from table order by sequence
");
Just loop threw them.