Laravel 排序结果按周分组

Laravel sort the result are grouped by weeks

有酒店预订申请。

我想获得 This Weeks 预订计数和 Last Weeks 预订计数。

所以我通过以下查询实现了这一点,该查询按周数给出了日期。我想整理一下。

查询:

$byweek = Reservation::all()->groupBy(function($date) {
                                    return Carbon::parse($date->check_in)->format('W');
                                });

输出是这样的:

这里 1617 是周数,我如何排序得到 1716

$byweek = Reservation::all()->groupBy(function($date) {
                                    return Carbon::parse($date->check_in)->format('W');
                                });

$byweek = $byweek->reverse();

完成

获取所有记录再逆向集合得到逆序17、16、15等。

我想你试试

$byweek = Reservation::all()
            ->groupBy(DB::raw('WEEK(created_at)'))
            ->orderBy(DB::raw('COUNT(id)','desc'));

Laravel 个集合 ->sortKeys()->sortKeysDesc() 中有方法。 https://laravel.com/docs/5.6/collections#method-sortkeys PHP 也有 ksort() 功能。

尝试在查询中使用 orderBy,它完美地工作如下:

$byweek = Reservation::orderBy('check_in')->get()->groupBy(function($date) {
                                return Carbon::parse($date->check_in)->format('W');
                            });

不要忘记您必须使用 get() 而不是 all()。 我尝试了这个方法,因为我希望每个星期内的对象都被订购并且它工作得很好。