2014-07-24 2 views
2

일 현재 주 내에서 생성 된 모든 레코드의 수를 얻기 위해 어떻게 created_at 타임 스탬프를 사용하여 laravel 어제의로 일주 오래된 작성된 레코드의 수를 싶어, 내가 가진 :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 일간의 레코드를 얻을 수있는 방법입니다.

답변

8

당신은뿐만 아니라 date()을 비교해야하고, 당신이 필요하지 않습니다하지만 그것은 탄소를 사용하는 것이 더 쉽습니다. 그것은 당신에게 달려 있습니다.

편집 : 질문이 약간 분명하지 않지만, 1 주일에 한 번만은 아니지만 현재 주간 결과 만 표시되는 것으로 보입니다. 어쨌든

이 당신을 위해 작동합니다

// 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'); 
2

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'); 
}