我需要按enum
字段对结果进行排序。这个称为status
的字段可以是open
、close
或edit
。现在,我想得到所有的条目,顺序是edit
,然后是open
,最后是close
。
拉拉韦尔·埃洛昆特有可能做到这一点吗?我试过这个(听起来很荒谬,但我想我应该试一试),但没有成功:
Survey::orderBy('status', 'edit', 'open', 'close')->get();
试试这个:
Survey::orderByRaw("FIELD(status, '"edit'", '"open'", '"close'")")->get();
对于postgres,请尝试以下操作:
Survey::orderByRaw("case status when 'edit' then 1 when 'open' then 2 when 'close' then 3 end")->get();
如果我们有asc
和desc
两个方向,请使用以下方法。
$priorities = ['high', 'medium', 'low'];
if ($request->get('order_direction', "asc") === "desc") {
$priorities = array_reverse($priorities);
}
$priorityString = implode('","', $priorities);
$query->orderByRaw('FIELD(priority, "' . $priorityString . '")');
查询它激发的desc
订单
select * from table order by FIELD(priority, "low","medium","high")
查询它激发的asc
订单
select * from table order by FIELD(priority, "high","medium","low")