Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to get custom sorted eloquent collection using whereIn method

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?

like image 562
Ahmed Raza Avatar asked Nov 13 '17 17:11

Ahmed Raza


People also ask

How to sort a collection in Laravel?

Laravel Sorting a collection 1 Sort () The sort method also allows for passing in a custom callback with your own algorithm. Under the hood sort uses php's usort. 2 SortBy () The sortBy method allows using dot notation format to access deeper key in order to sort a multi-dimensional array. 3 SortByDesc ()

How to use Laravel eloquent wherein with arrays?

And as well as how to use laravel eloquent wherein with arrays. The following syntax represents the whereIn eloquent method in laravel: Column_name:- Your database table column name. Array: – array with comma-separated values. Let’s take look at some example of whereIn () eloquent method in laravel:

What is the difference between wherein () and array () method in Laravel?

Column_name:- Your database table column name. Array: – array with comma-separated values. Let’s take look at some example of whereIn () eloquent method in laravel: In this query, the data will be get from the DB table. Whose ids will be 10, 15, 18.

What is the difference between array and column_name in Laravel?

Column_name:- Your database table column name. Array: – array with comma-separated values. Let’s take look at some example of whereIn () eloquent method in laravel: In this query, the data will be get from the DB table.


1 Answers

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

like image 87
M Khalid Junaid Avatar answered Oct 09 '22 09:10

M Khalid Junaid