laravel eloquent 获取最近 3 小时内的记录

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

eloquent fetch records within recent 3 hours

phplaraveleloquent

提问by vijayrana

I need to fetch all the records which is inserted between past 3 hours to current(now). I am using laravel framework(eloquent orm).

我需要获取在过去 3 小时到当前(现在)之间插入的所有记录。我正在使用 Laravel 框架(雄辩的 orm)。

I tried this found here

我试过这个发现here

$lb = \DB::table('myTable')->whereRaw('created_at = DATE_ADD(NOW(), INTERVAL -3 HOUR');

But it return NULL. Is there any way I can do using eloquent but not Raw Query?

但它返回NULL。有什么办法可以使用 eloquent 而不是 Raw Query?

Any Help would be appreciated.

任何帮助,将不胜感激。

采纳答案by Alok Patel

We can use PHP DateTime. Like this,

我们可以使用 PHP DateTime。像这样,

$date = new \DateTime();
$date->modify('-3 hours');
$formatted_date = $date->format('Y-m-d H:i:s');
$lb = \DB::table('myTable')->where('created_at', '>',$formatted_date);

In above code what we're doing is creating date string with PHP and using that in query.

在上面的代码中,我们正在做的是用 PHP 创建日期字符串并在查询中使用它。

回答by Chris

Laravel comes with Carbon, a nice library to handle dates, which can be used in combination with Eqlouent.

Laravel 附带了 Carbon,这是一个处理日期的好库,可以与 Eqlouent 结合使用。

Example:

例子:

\DB::table('myTable')
    ->where('created_at', '>', 
        Carbon::now()->subHours(3)->toDateTimeString()
    );

More Information

更多信息

For more fun date methods, check out these docs on Carbon http://carbon.nesbot.com/docs/#api-addsub

有关更多有趣的日期方法,请查看 Carbon http://carbon.nesbot.com/docs/#api-addsub上的这些文档

回答by Rakesh Kumar

Try This

尝试这个

$lb = \DB::table('myTable')->whereRaw('created_at >= DATE_SUB(NOW(), INTERVAL 3 HOUR)')

In your statement you are using =(206-07-27 11:30:00) instead >=(206-07-27 11:30:00)

在您的声明中,您使用=(206-07-27 11:30:00) 代替>=(206-07-27 11:30:00)

回答by Akram Wahid

try this, include use Illuminate\Support\Facades\DB;namespace in your controller

试试这个,use Illuminate\Support\Facades\DB;在你的控制器中包含命名空间

and try this code

并尝试此代码

$results = DB::table('yourtable')->select('*')->where('created_at >= DATE_SUB(NOW(),INTERVAL 1 HOUR)')->get();

回答by ananimattor

as created_at is datetime field, you can use this

由于 created_at 是日期时间字段,您可以使用它

\DB::table('myTable')->where('created_at', '<', Carbon::now()->subHours(3)->toDateTimeString())->get();