简体   繁体   English

Laravel 集合 sortBy 不生效

[英]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;
});

就我而言,这是一个巨大的失败,我漂亮的打印 JSON chrome 扩展程序弄乱了显示顺序,查看原始响应表明它们实际上已正确排序... ::facepalm::

To extend on @Titan's answer, i guess the extensions/ postman maintain the array indexing order.为了扩展@Titan 的回答,我猜扩展名/邮递员会维护数组索引顺序。 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.这将获得所需的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM