Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel collection sortBy not taking effect

I'm trying to combine and sort the results from several db queries.

$events = collect();

$downedEvents = EventDowned::where('mission', $missionId)
   ->orderBy('mission_time', 'asc')
   ->get();

$events->push($downedEvents);

$getInOutEvents = EventGetInOut::where('mission', $missionId)
   ->orderBy('mission_time', 'asc')
   ->get();

$events->push($getInOutEvents);

$missileEvents = EventMissile::where('mission', $missionId)
   ->orderBy('mission_time', 'asc')
   ->get();

$events->push($missileEvents);

$flattenedEvents = $events->flatten();
$sortedEvents = $flattenedEvents->sortBy('mission_time');

return $sortedEvents->all();

The result looks like this:

ss

As you can see it has correctly combined the results, however they remain in their original query order, not sorted.

I've also tried

$sortedEvents = $flattenedEvents->sortBy(function($event) {
    return (int) $event->mission_time;
});
like image 327
Titan Avatar asked Mar 12 '17 22:03

Titan


2 Answers

To extend on @Titan's answer, i guess the extensions/ postman maintain the array indexing order. Not really sure.

To get rid of that

return $collection->values();

Here is an example

$arr = collect([
  0 => [
      'name' => 'foo',
      'weight' => 70
  ],
  1 => [
      'name' => 'bar',
      'weight' => 80
  ]
 ]);

return $arr->sortByDesc('weight');

the extension will still keep the index order

return $arr->sortByDesc('weight')->values();

This will get the desired order.

like image 83
f_i Avatar answered Nov 16 '22 03:11

f_i


A huge fail on my part, my pretty print JSON chrome extension was messing with the display order, viewing the raw response showed they were in fact sorted correctly... ::facepalm::

like image 27
Titan Avatar answered Nov 16 '22 03:11

Titan