2017-05-31 430 views
1

當我使用orderByRaw函數時,Eloquent/QueryBuilder出現問題我得到的異常列不存在,但該列已存在於數據庫中。Laravel 5,orderByRaw使用字段和列不存在

這裏是個例外:

SQLSTATE[42883]: Undefined function: 7 ERROR: function field(integer, integer) does not exist 
HINT: No function matches the given name and argument types. You might need to add explicit type casts. 

狀態列到數據庫是整數。 這裏是我的代碼:

$orderedStatuses = implode(',', [4]); 
$users->orderByRaw(\DB::raw("FIELD(status, $orderedStatuses)")); 

...也是,如果我使用users.status我得到了同樣的錯誤。

有人可以幫助我嗎?

感謝

+0

'orderByRaw'已經預計原始的SQL。你也不需要在裏面使用'DB :: raw'。 – fubar

+0

另外,對於fubar寫的,MySQL [FIELD()](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_field)函數接受字符串作爲參數。顯然,你傳遞的是整數。錯誤消息沒有提到你提到的不存在的列。這是關於錯誤使用的功能。 – lesssugar

回答

0

orderByRaw預計原始的SQL,你必須通過字符串中的orderByRaw的說法。

實施例:

$users->orderByRaw('field1 ASC, field2 DESC, field3 DESC,...'); 
1

您混合這兩種方法。

$users->orderBy(\DB::raw("FIELD(status, $orderedStatuses)")); 

或者

$users->orderByRaw("FIELD(status, $orderedStatuses)");