简体   繁体   中英

Get Last n Months Data Group by Week - Laravel

I am trying to get last 4 months data filtered by week in Laravel. This is code I currently have:

$analytics =
        Data::select([
            DB::raw('WEEK(p_date_time) AS week'),
            DB::raw('COUNT(id) AS count'),
        ])
            ->where('p_id', $p_id)
            ->where('p_date_time', '>=', Carbon::now()->subMonth(4))
            ->groupBy('week')
            ->orderBy('week')
            ->get()
            ->toArray();

This code gives me 52 results based on Data for 1 full year (As I am using WEEK). But I need around 17 results for the last 4 months.

I can make that happen by gathering of each day and then adding 7 days data as chunk for last 4 months, but how can I do it with query alone?

Thanks.

Maybe just a typo in your Carbon query. Change subMonth(4) to subMonths(4) . With 's'.

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