Laravel:如何使用whereIn方法获取自定义排序的雄辩集合 [英] Laravel: How to get custom sorted eloquent collection using whereIn method
问题描述
我有一个需要检索其模型集合的产品ID数组.数组是这样的:
I have an array of product ids against which I need to retrieve the model collection. The array is something like this:
$ids = array(9, 2, 16, 11, 8, 1, 18);
现在,我正在使用以下代码行来获取集合.
Right now, I'm using the following line of code to get the collection.
$products = Product::whereIn('id', $ids)->get();
但是它将根据产品ID对产品进行排序.例如:1, 2, 8, 9, 11, 16, 18
.我需要的是与$ids
数组中相同的顺序,即9, 2, 16, 11, 8, 1, 18
.
But it sorts the products against their ids. such as: 1, 2, 8, 9, 11, 16, 18
. What I need is the same order as in the $ids
array i.e 9, 2, 16, 11, 8, 1, 18
.
我应该怎么做才能获得与数组中相同的顺序?
What should I do to get the same order as in the array?
推荐答案
使用mysql的Field()
函数(如果使用的是mysql数据库)与laravel的DB::raw()
类似
Use Field()
function of mysql (If you are using mysql database) with DB::raw()
of laravel something like
$products = Product::whereIn('id', $ids)
->orderBy(DB::raw("FIELD(id,".join(',',$ids).")"))
->get();
Field()
返回索引逗号分隔列表的位置
Field()
returns the index position of a comma-delimited list
这篇关于Laravel:如何使用whereIn方法获取自定义排序的雄辩集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!