如何在 Laravel 5.3 中的collect中使用groupBy之后的sortBy?

myS*_*Sun 2 laravel laravel-5.3

groupBy('date')我需要在使用 Eloquent、create和sortBy('price')in获取 sql 查询collectLaravel 5.3

IndexController

$flights = Flights::GetFlights($fromCity, $toCity, $fromDate);

$collection = collect($flights);

$sortFlight = $collection->groupBy('date')->sortBy('price');
Run Code Online (Sandbox Code Playgroud)

Model

public function scopeGetFlights($query, $fromCity, $toCity, $fromDate)
{
    // Between dates
    $beforeDate = date('Y-m-d', strtotime($fromDate . '- 10 days'));
    $afterDate = date('Y-m-d', strtotime($fromDate . '+ 10 days'));

    $join = $query
        -> join('airlines', 'airlines.pana', 'flights.airline')
        -> where('flights.from_city', $fromCity)
        -> where('flights.to_city', $toCity)
        -> whereBetween('flights.date', [$beforeDate, $afterDate])
        -> get([
                 'flights.*',
                 'airlines.pana as pana',
                 'airlines.name as airlineName'
              ]);
    return $join;
}
Run Code Online (Sandbox Code Playgroud)

然后Print_r($sortFlight),打印后groupBy('date')可以工作但sortBy('price')不起作用!!!!

我的问题出在哪里?

sub*_*ign 5

我在 Laravel 中对分组集合中的值进行排序的解决方案

$sponsors = Sponsor::with('sponsor_level')->whereStatus(1)->get();

// grouped by sponsor level name
$grouped = $sponsors->sortBy('sponsor_level.order')->groupBy(function($item, $key){
    return $item->sponsor_level->name;
});

// finally sorted by sponsor name inside the group
return $grouped->map(function($item, $key){
    return $item->sortBy('name');
});
Run Code Online (Sandbox Code Playgroud)

当然,您可以将它们链接起来,为了更好的可读性,我将其分开。