简体   繁体   中英

How to get all results that fall under each weeks based on given date for the past 6 months using laravel and carbon

I have many records created each day and I would like to know how many records are completed for each week based on the date created. The query perhaps would be something like this

$records_weekly = DB::table('records')

   ->where('created_at', '>=', Carbon::now()->subMonths(4))

   ->groupBy('week')

   ->get()

   ->toArray();

I hope u are having eloquent:

$date = Carbon::now();

$records_weekly = Records::all()->where('created_at', '>=', Carbon::now()->subMonths(4))
                            ->groupBy(function($date) {
                                return Carbon::parse($date->created_at)->format('W');
                            })->sortKeysDesc();

This will product output like, note 20 , 21 , 22 are week numbers

{
    "20": [...],
    "21": [...],
    "22": [
           {
            "id": 19,
            .....
            "created_at": "2018-05-31 07:46:33",
            "updated_at": "2018-05-23 07:46:33"
           }
          ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM