在 Eloquent where 子句 Laravel 5 中计算日期差异

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

Calculate date diff in Eloquent where clause Laravel 5

phplaraveleloquentdatediff

提问by Bellots

In my Laravel 5 app I've got a relationship, and from this one-to-many relationship, I want to query and get only results whose date diff between their creation_date and an arbitrary date is between 0 and 2 days.

在我的 Laravel 5 应用程序中,我有一个关系,并且从这个一对多关系中,我想查询并只获取其 creation_date 和任意日期之间的日期差异在 0 到 2 天之间的结果。

If you need I can show you a pseudocode, even if I think that it's clear what I need.

如果您需要,我可以向您展示伪代码,即使我认为这很清楚我需要什么。

Thank you!

谢谢!

回答by Arthur Samarcos

Just create a arbitrary date using carbon (as you are using laravel):

只需使用 carbon 创建一个任意日期(就像您使用 laravel 一样):

$start = Carbon\Carbon::create(year,month,day);

$end = $start->copy()->addDays(2);

And a little DB::raw in the mix, to format the created_at field to your needs:

和一些 DB::raw 混合,根据您的需要格式化 created_at 字段:

Model::where(DB::raw('DATE_FORMAT(created_at,"%Y-%m-%d")'),'>=',$start)->where(DB::raw('DATE_FORMAT(created_at,"%Y-%m-%d")'),'<=',$end)->get();    

That's it.

就是这样。