Skip to content

Instantly share code, notes, and snippets.

@omitobi
Created August 30, 2018 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omitobi/5fb47b68e8fd8635022d77fc1689d2e6 to your computer and use it in GitHub Desktop.
Save omitobi/5fb47b68e8fd8635022d77fc1689d2e6 to your computer and use it in GitHub Desktop.
maintain the order of queried records
$users_ids = [1,3,2];
$items = collect($users_ids);
$fields = $items->map(function ($ids){
return '?';
})->implode(',');
$ordered = User::orderbyRaw("FIELD (id, ".$fields.")", $items->prepend('id'))
->find($users_ids)->pluck('id');
//ordered should be [1,3,2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment