检索上个月的所有行(Laravel + Eloquent)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46096260/
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
Retrive all rows from last month (Laravel + Eloquent)
提问by Klaus
I'm trying to get all records that belongs to last month, so far I managed to get all from last month but to date today, I'm not sure how I can get only for last month
我正在尝试获取属于上个月的所有记录,到目前为止,我设法获取了上个月的所有记录,但到目前为止,我不确定如何仅获取上个月的记录
$revenueMonth = Callback::where('created_at', '>=', Carbon::today()->startOfMonth()->subMonth())->sum('payment');
采纳答案by Odin Thunder
More clear solution for your problem:
更清晰的解决您的问题:
$revenueMonth = Callback::whereMonth(
'created_at', '=', Carbon::now()->subMonth()->month
);
回答by Klaus
None of the answers get's me to where I'm looking to go :(.
没有一个答案能让我到达我想去的地方:(。
I have a solution but I think it's ugly and hoped it could be made more clean
我有一个解决方案,但我认为它很丑,希望它可以变得更干净
$fromDate = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$tillDate = Carbon::now()->subMonth()->endOfMonth()->toDateString();
$revenueLastMonth = Callback::whereBetween(DB::raw('date(created_at)'), [$fromDate, $tillDate])->get();
This will give my the result I'm looking for, here is my records:
这会给我我正在寻找的结果,这是我的记录:
2017-09-07 09:46:43
2017-09-07 09:46:43
2017-09-07 09:46:43
2017-09-02 09:46:43
2017-08-07 09:46:43
And I want it to return ONLY what records is made in August 2017 (2017-08-07 09:46:43)
我希望它只返回 2017 年 8 月的记录 (2017-08-07 09:46:43)
回答by Odin Thunder
Try this solutions:
试试这个解决方案:
$revenueMonth = Callback::where(
'created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString()
);
You get all Callback for last 30 days.
您会收到过去 30 天的所有回调。
$revenueMonth = Callback::where(
'created_at', '>=', Carbon::now()->firstOfMonth()->toDateTimeString()
);
Get for current month.
获取当月。
$revenueMonth = Callback::where(
'created_at', '>=', Carbon::now()->startOfMonth()->subMonth()->toDateString()
);
Get for start last month.
上个月开始。
UPDATED
更新
$revenueMonth = Callback::where(
'created_at', '>=', Carbon::now()->subMonth()->toDateTimeString()
);
This is what are you looking for :)
这就是你要找的:)
Hope it will help you:)
希望能帮到你:)
回答by Odin Thunder
UPDATEDeloquent version of the your answer
更新了你的答案的雄辩版本
$fromDate = Carbon::now()->subMonth()->startOfMonth()->toDateString();
$tillDate = Carbon::now()->subMonth()->endOfMonth()->toDateString();
$revenueLastMonth = Callback::whereBetween('created_at',[$fromDate,$tillDate])->get();