Laravel:如何计算截至昨天本周内创建的所有记录

时间:2014-07-24 05:05:13

标签: php mysql sql laravel laravel-4

我希望使用created_at时间戳来记录昨天在laravel中创建的一周的记录,我有:

//week date range upto current day
$name_current_day = date("l");
$name_current_week = date("Y-m-d",strtotime('monday this week')).'to'.date("Y-m-d",strtotime("$name_current_day this week"));

//query to get count
foreach($name_list as $name){
                //created in week
                $data[$network->name.'_week'] = Info::select( DB::raw('DATE(`created_at`) as `date`'),DB::raw('COUNT(*) as `count`'))
                    ->where('created_at', '>', $name_current_week)
                    ->where('name',$name->f_name)
                    ->groupBy('date')
                    ->orderBy('date', 'DESC')
                    ->lists('count', 'date');
           }

当我运行此查询时,我得不到准确的结果,这是在Laravel中获取最近7天记录的正确方法。

2 个答案:

答案 0 :(得分:10)

您还需要比较date(),并且使用Carbon更容易,但您不需要。这取决于你。

编辑:您的问题有点不清楚,但似乎您不想要一周,但只需要本周的结果。

无论如何,这对你有用:

// week old results:
// $fromDate = Carbon\Carbon::now()->subDays(8)->format('Y-m-d');
// $tillDate = Carbon\Carbon::now()->subDay()->format('Y-m-d');

// this week results
$fromDate = Carbon\Carbon::now()->subDay()->startOfWeek()->toDateString(); // or ->format(..)
$tillDate = Carbon\Carbon::now()->subDay()->toDateString();


Info::selectRaw('date(created_at) as date, COUNT(*) as count'))
    ->whereBetween( DB::raw('date(created_at)'), [$fromDate, $tillDate] )
    ->where('name',$name->f_name)
    ->groupBy('date')
    ->orderBy('date', 'DESC')
    ->lists('count', 'date');

答案 1 :(得分:3)

您可以使用Carbon,这样可以更轻松地在Laravel中使用日期。它包含在框架中。然后你可以这样做:

$yesterday = Carbon::now()->subDays(1);
$one_week_ago = Carbon::now()->subWeeks(1);

foreach($name_list as $name){
    //created in week
    $data[$network->name.'_week'] = Info::select( DB::raw('DATE(`created_at`) as `date`'),DB::raw('COUNT(*) as `count`'))
        ->where('created_at', '>=', $one_week_ago)
        ->where('created_at', '<=', $yesterday)
        ->where('name',$name->f_name)
        ->groupBy('date')
        ->orderBy('date', 'DESC')
        ->lists('count', 'date');
}