How to make Laravel whereIn not sorted automatically

时光毁灭记忆、已成空白 提交于 2019-12-08 03:06:26
Lionel Chan

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

EddyTheDove

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.

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