Laravel 5.4:如何获取本周的记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44473685/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:06:50  来源:igfitidea点击:

Laravel 5.4: How do I get records from just this week?

laravellaravel-5.4

提问by anonym

To get all records of the current day, I did

为了获得当天的所有记录,我做了

$dt = Carbon::now();
$dataToday = Data::whereDay('created_at', $dt->day)->get();

To get records from this week, I tried the following but without success.

为了获得本周的记录,我尝试了以下但没有成功。

$dataThisWeek = Data::where('created_at', $dt->weekOfYear);
$dataThisWeek = Data::where('created_at', $dt->weekOfMonth);
$dataThisWeek = Data::whereWeek('created_at', $dt->week);

How do we approach this with Eloquent and Carbon (preferably) or a native MYSQL function?

我们如何使用 Eloquent 和 Carbon(最好)或本机 MYSQL 函数来解决这个问题?

回答by

Try this:

尝试这个:

Data::whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();

To set the week start/end:

设置周开始/结束:

Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);

回答by ayip

You can also try

你也可以试试

$dataThisWeek = Data::where(\DB::raw("WEEKOFYEAR(created_at)"), $dt->weekOfYear)->get();