0

I have a collection of ids as follows:

array:2 [
  0 => "102"
  1 => "101"
]

Please notice that order matters.

When I query the model like:

$models = Post::whereIn('id', $keys)->get();

it loses the order.

So I expect that post with id 102 comes before 101 but 101 comes first.

How can I force query builder to keep the order

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mehrdad Shokri
  • 1,974
  • 2
  • 29
  • 45
  • 2
    The order of the IDs in an `IN` statement do not determine the order of the results. You'll need to use an `orderBy` statement to accomplish that. – The Maniac Oct 25 '16 at 19:54
  • Can you provide an example? – Mehrdad Shokri Oct 25 '16 at 19:55
  • 1
    It depends, what are you trying to order your results by? Just in case, documentation [can be found here](https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset). – The Maniac Oct 25 '16 at 19:58

2 Answers2

0

Use the orderBy() method on the id column

$models = Post::whereIn('id', $keys)->orderBy('id', 'ASC')->get();

Angad Dubey
  • 5,067
  • 7
  • 30
  • 51
0

You can do something like this:

$ids_ordered = implode(',', $keys);

$models = Post::whereIn('id', $keys)
              ->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
              ->get();

Reference FIELD()

Amit Gupta
  • 17,072
  • 4
  • 41
  • 53