Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 Get records the same ordering as in whereIn()

I have this array with record IDs:

$record_ids = [60, 66, 70, 64, 69, 67, 65, 57];

And I get rows by using model, like this:

$result = Model::whereIn('id', $record_ids)->get();

The problem - I want to get rows the same order as in my $record_ids array. Laravel returns me these rows in ascending ID order like this:

[57, 60, 64, 65, 66, 67, 69, 70]

How to do that? How to make Laravel "Not to order by ID ASC by default"? Thanks.

like image 604
Valters Avatar asked Apr 16 '16 12:04

Valters


People also ask

What does get () return in laravel?

Think of it like this: when you don't exactly know what a query will return then you need to use get() . For example you can't use it with all() since you know that it will return all the records and no further conditions can be applied. It's the same with find() since you know it will only try to fetch one record.

What is Take () in laravel?

you can easily use it with laravel 6 and laravel 7 application. take() will help to get data from a database table with a limit. skip() will help to skip some records when you fetch data from the database table.

What is difference between Pluck and select in laravel?

Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array. Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.

What is toArray in laravel?

toArray is a model method of Eloquent, so you need to a Eloquent model, try this: User::where('name', '=', 'Jhon')->get()->toArray(); http://laravel.com/docs/eloquent#collections. Follow this answer to receive notifications.


2 Answers

You can use orderByRaw() like as

$result = Model::whereIn('id', $record_ids)
          ->orderByRaw("field(id,".implode(',',$record_ids).")")
          ->get();
like image 151
Narendrasingh Sisodia Avatar answered Nov 14 '22 23:11

Narendrasingh Sisodia


use the sortBy method in the collection, you can order by an array of ids.

$theIds = [2,76,423];

$collection = $collection->sortby(function($model) use ($theIds){
   return array_search($model->id, $theIds);
});

it would probally be best to slice the $record_ids this would act as a offset and limit then sort the returned collection once the query has been run.

like image 41
David Clews Avatar answered Nov 14 '22 22:11

David Clews