Valters
Valters

Reputation: 79

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.

Upvotes: 7

Views: 3051

Answers (2)

David Clews
David Clews

Reputation: 906

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.

Upvotes: 4

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

You can use orderByRaw() like as

$result = Model::whereIn('id', $record_ids)
          ->orderByRaw("field(id,".implode(',',$record_ids).")")
          ->get();

Upvotes: 18

Related Questions