5

my array from $temp is Array ( [0] => 22 [1] => 26 [2] => 20 [3] => 24 ) or 22|26|20|24

when I use whereIn like this

$robjeks = DB::table('objek')->whereIn('id', $temp)->get();

the result is 20|22|24|26|

it's automatically sorted. I want it's not sorted.

how to make it same like 22|26|20|24?

thanks for your attention.

Mading Ne
  • 133
  • 2
  • 13
  • 2
    Possible duplicate of [Laravel MySQL how to order results in the same order as in whereIn clause](http://stackoverflow.com/questions/26176245/laravel-mysql-how-to-order-results-in-the-same-order-as-in-wherein-clause) – Lionel Chan Jan 17 '17 at 03:45
  • which are the other fields in 'objek' table? – mith Jan 17 '17 at 03:56
  • Possible duplicate of [Laravel loses order when querying](http://stackoverflow.com/questions/40248553/laravel-loses-order-when-querying/40250833) – Amit Gupta Jan 17 '17 at 03:59

2 Answers2

3

This has nothing to do with Laravel. Read here first: avoid Sorting by the MYSQL IN Keyword

Then, to do this, you can use this code:

$temp = [22, 26, 20, 24];
$tempStr = implode(',', $temp);
$robjeks = DB::table('objek')
    ->whereIn('id', $temp)
    ->orderByRaw(DB::raw("FIELD(id, $tempStr)"))
    ->get();

You might be in risk with sql injection in this case, so please sanitize the array of numbers accordingly.

Ref: Laravel: order by where in

Community
  • 1
  • 1
Lionel Chan
  • 7,894
  • 5
  • 40
  • 69
1

I think it has more to do with SQL rather than Laravel. If you are using autoincrement id, then obviously 22 is found before 26. If you want to change that you may follow this link: Laravel: order by where in

Or manually order your query yourself. eg.: ->orderBy('name') or something else.

Community
  • 1
  • 1
EddyTheDove
  • 12,979
  • 2
  • 37
  • 45