How to make Laravel whereIn not sorted automatically

↘锁芯ラ 提交于 2019-12-23 03:33:29

问题


my array from $temp is Array ( [0] => 22 [1] => 26 [2] => 20 [3] => 24 ) or 22|26|20|24

when I use whereIn like this

$robjeks = DB::table('objek')->whereIn('id', $temp)->get();

the result is 20|22|24|26|

it's automatically sorted. I want it's not sorted.

how to make it same like 22|26|20|24?

thanks for your attention.


回答1:


This has nothing to do with Laravel. Read here first: avoid Sorting by the MYSQL IN Keyword

Then, to do this, you can use this code:

$temp = [22, 26, 20, 24];
$tempStr = implode(',', $temp);
$robjeks = DB::table('objek')
    ->whereIn('id', $temp)
    ->orderByRaw(DB::raw("FIELD(id, $tempStr)"))
    ->get();

You might be in risk with sql injection in this case, so please sanitize the array of numbers accordingly.

Ref: Laravel: order by where in




回答2:


I think it has more to do with SQL rather than Laravel. If you are using autoincrement id, then obviously 22 is found before 26. If you want to change that you may follow this link: Laravel: order by where in

Or manually order your query yourself. eg.: ->orderBy('name') or something else.



来源:https://stackoverflow.com/questions/41688648/how-to-make-laravel-wherein-not-sorted-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!