14

我正在尝试对多个数据库查询的结果进行组合和排序。

$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();

结果如下所示:

ss

如您所见,它已正确组合结果,但它们仍保持原始查询顺序,未排序。

我也试过

$sortedEvents = $flattenedEvents->sortBy(function($event) {
    return (int) $event->mission_time;
});
4

2 回答 2

26

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

于 2017-03-13T19:32:38.537 回答
26

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

摆脱那个

return $collection->values();

这是一个例子

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

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

扩展仍将保持索引顺序

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

这将获得所需的顺序。

于 2019-04-11T09:36:49.293 回答