Laravel:如何获取截至昨天的本周内创建的所有记录的计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24925511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: How to get count of all records created within in current week as of yesterday
提问by user3871434
I want to get count of one week old created records as of yesterday in laravel using created_at time stamp, I have:
我想使用 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');
}
When I run this query, I am not getting accurate results, Is this the cirrect way to get last 7 days records in Laravel.
当我运行这个查询时,我没有得到准确的结果,这是在 Laravel 中获取最近 7 天记录的正确方法吗?
回答by Jarek Tkaczyk
You need to compare date()
as well, and it's easier to use Carbon, though you don't need that. It's up to you.
您还需要进行比较date()
,使用 Carbon 更容易,尽管您不需要那样。由你决定。
EDIT:your question is a bit unclear, but it seems that you don't want week-old, but only current week's results.
编辑:您的问题有点不清楚,但似乎您不想要一周的结果,而只想要本周的结果。
Anyway, this will work for you:
无论如何,这对你有用:
// 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');
回答by lowerends
You can use Carbon for this, which makes working with dates easier in Laravel. It's included with the framework. You can then do this:
您可以为此使用 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');
}