Laravel 集合 sortBy 不生效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42754075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:32:55  来源:igfitidea点击:

Laravel collection sortBy not taking effect

phplaravellaravel-5eloquentlaravel-collection

提问by Titan

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

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;
});

回答by Titan

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::

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

回答by f_i

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

为了扩展@Titan 的回答,我猜扩展名/邮递员会维护数组索引顺序。不太确定。

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.

这将获得所需的顺序。