Laravel 集合排序方式未生效
Laravel collection sortBy not taking effect
我正在尝试合并和排序来自多个数据库查询的结果。
$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();
结果如下所示:
如您所见,它已正确组合结果,但它们仍保持原始查询顺序,未排序。
我也试过了
$sortedEvents = $flattenedEvents->sortBy(function($event) {
return (int) $event->mission_time;
});
我的一个巨大失败,我漂亮的打印 JSON chrome 扩展扰乱了显示顺序,查看原始响应显示它们实际上排序正确... ::facepalm ::
为了扩展@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();
这将获得所需的顺序。
我正在尝试合并和排序来自多个数据库查询的结果。
$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();
结果如下所示:
如您所见,它已正确组合结果,但它们仍保持原始查询顺序,未排序。
我也试过了
$sortedEvents = $flattenedEvents->sortBy(function($event) {
return (int) $event->mission_time;
});
我的一个巨大失败,我漂亮的打印 JSON chrome 扩展扰乱了显示顺序,查看原始响应显示它们实际上排序正确... ::facepalm ::
为了扩展@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();
这将获得所需的顺序。