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.
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.
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.
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.
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.
You can use orderByRaw()
like as
$result = Model::whereIn('id', $record_ids)
->orderByRaw("field(id,".implode(',',$record_ids).")")
->get();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With