簡體   English   中英

Laravel Eloquent - 按枚舉字段排序

[英]Laravel Eloquent - Order by Enum Field

我需要按enum字段排序我的結果。 此字段稱為status可以是opencloseedit 現在,我想獲取所有條目,使用edit ,然后open ,最后close訂單。

這對 Laravel Eloquent 可行嗎? 我試過這個(這聽起來很荒謬,但我想我會試一試),但沒有奏效:

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();

如果我們有ascdesc兩個方向,請使用以下方法。

$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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM