Laravel: How to get custom sorted eloquent collect

2019-02-22 04:42发布

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

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?

2条回答
再贱就再见
2楼-- · 2019-02-22 04:59

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() returns the index position of a comma-delimited list

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-22 05:10

Here's another way to do that.

$ids = array(9, 2, 16, 11, 8, 1, 18);
$products = User::whereIn('id', $ids)->orderByRaw('FIELD(id, '.implode(',', $ids).')')->get();
查看更多
登录 后发表回答