如何使Laravel whereIn不自动排序 [英] How to make Laravel whereIn not sorted automatically

查看:349
本文介绍了如何使Laravel whereIn不自动排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自$temp的数组是Array ( [0] => 22 [1] => 26 [2] => 20 [3] => 24 )22|26|20|24

当我这样使用whereIn

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

结果是20|22|24|26|

它会自动排序.我希望它没有排序.

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

如何使其像22|26|20|24一样?

感谢您的关注.

推荐答案

这与Laravel无关.首先阅读这里:避免按MYSQL IN关键字排序

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

在这种情况下,您可能会遇到sql注入的风险,因此请相应地清理数字数组.

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

参考: Laravel:按在何处排序

这篇关于如何使Laravel whereIn不自动排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆