将日期=今天的项目放在收藏的第一位(Laravel)
我有一个所有事件的集合将日期=今天的项目放在收藏的第一位(Laravel),laravel,eloquent,laravel-collection,Laravel,Eloquent,Laravel Collection,我有一个所有事件的集合$events=App\Event::orderByDesc('start\u date')->get()。现在我想把今天的事件放在第一位,同时保持其他事件的顺序。我想我应该使用reject()和prepend(),但我不能同时使用这两种方法。您可以尝试使用如下收集方法: // Create 2 collections, One for today's event and another for the other days list($todays, $otherDays
$events=App\Event::orderByDesc('start\u date')->get()
。现在我想把今天的事件放在第一位,同时保持其他事件的顺序。我想我应该使用reject()
和prepend()
,但我不能同时使用这两种方法。您可以尝试使用如下收集方法:
// Create 2 collections, One for today's event and another for the other days
list($todays, $otherDays) = App\Event::orderByDesc('start_date')->get()->partition(function($event){
// NOTE: change the date comparison as necessary such as date format. I assume you use carbon here
return $event->start_date === \Carbon\Carbon::today()->toDateString();
}
$events = $todays->merge($otherDays);
作为替代方案,我发现它使用了拒绝方法。对于您的情况,代码如下所示:
$filterFunc = function($event){
return $event->start_date === \Carbon\Carbon::today()->toDateString();
}
$collection = App\Event::orderByDesc('start_date')->get();
$events = $collection->filter($filterFunc)->merge($collection->reject($filterFunc));