Laravel Eloquent 在当前月份和前 3 个月之间选择

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

Laravel Eloquent Select Between current month and previous 3 months

laravellaravel-5eloquentphp-carbon

提问by Lloyd Owen

i'm trying to build a query that will select all of the records in my DB between now (current month) and the previous 3 months.

我正在尝试构建一个查询,该查询将选择现在(当月)和前 3 个月之间我的数据库中的所有记录。

My query somewhat works, but i want to ignore the day of the month. At the moment, it's selecting the last # of months to the current DAY as well but i want to ignore the current day and use the start and end of the months.

我的查询有点有效,但我想忽略一个月中的哪一天。目前,它也在选择当前日期的最后几个月,但我想忽略当前日期并使用月份的开始和结束时间。

Here's my query:

这是我的查询:

$dateS = Carbon::now()->subMonth(3);
$dateE = Carbon::now(); 
$TotalSpent = DB::table('orders')
->select('total_cost','placed_at')
->whereBetween('placed_at',[$dateS,$dateE])
->where(['deleted' => '0', 'delivery_address_id' => $DeliveryAddress->id])
->sum('total_cost');

Any help would be appreciated. It's really bugging me!

任何帮助,将不胜感激。真是烦死我了!

回答by Mr. Pyramid

This will do the trick I guess

我猜这会解决问题

$dateS = Carbon::now()->startOfMonth()->subMonth(3);
$dateE = Carbon::now()->startOfMonth(); 
$TotalSpent = DB::table('orders')
->select('total_cost','placed_at')
->whereBetween('placed_at',[$dateS,$dateE])
->where(['deleted' => '0', 'delivery_address_id' => $DeliveryAddress->id])
->sum('total_cost');

startOfMonth()begins with 1st date of the month

startOfMonth()从当月的第一个日期开始