Laravel and MySQL get data by week

问题: I have this function that gets the data from MySQL by month using carbon $calls = DB::table('calls') ->where('owned_by_id', $report->id) ->wher...

问题:

I have this function that gets the data from MySQL by month using carbon

$calls = DB::table('calls') 
        ->where('owned_by_id', $report->id) 
        ->where(DB::raw('month(created_at)'), Carbon::today()->month)
        ->get();
        $report->callsCount = $calls->count();

It works fine what i want to do is to get the data per week

I tried modifying the code like this:

   ->where(DB::raw('week(created_at)'), Carbon::today()->week)

but i get an error in Laravel

Unknown getter 'week'


回答1:

Look you need to filter date by week which mean date range try this

$calls = DB::table('calls') 
    ->where('owned_by_id', $report->id) 
    ->whereBetween('created_at', [Carbon::now()->subWeek()->format("Y-m-d H:i:s"), Carbon::now()])
    ->get();
$report->callsCount = $calls->count();

This mean to get all data from last 7 days to now based on carbon docs https://carbon.nesbot.com/docs/ and laravel docs https://laravel.com/docs/5.8/queries#where-clauses


回答2:

Use whereBetween with two carbon date instances.

->whereBetween('created_at', [
    CarbonCarbon::parse('last monday')->startOfDay(),
    CarbonCarbon::parse('next friday')->endOfDay(),
])

回答3:

Like @Abrar says, if you need to count total calls of the current month u can use whereBetween:

$calls = DB::table('calls') 
        ->where('owned_by_id', $report->id) 
        ->whereBetween('created_at', [
            now()->locale('en')->startOfWeek(),
            now()->locale('en')->endOfWeek(),
        ])
        ->get();
$report->callsCount = $calls->count();

But u want to count the total numerb of calls per each week u need to use groupBy. Good luck!

  • 发表于 2019-03-16 04:08
  • 阅读 ( 48 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除