Laravel/Eloquent 和比较日期

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

Laravel/Eloquent and comparing dates

laraveleloquent

提问by sehummel

I want to return all of the rows in my database table that are a day or less old. I'm using Laravel 4. This is what I tried:

我想返回数据库表中一天或更短的所有行。我正在使用 Laravel 4。这是我尝试过的:

$date = date('Y-m-d H:i:s');
return MainContact::where(DATEDIFF('timestamp', $date), '<=', 1)->get();

This doesn't work. I read the documentation and it doesn't seem like you can pass Laravel MySQL functions. timestampis a datetime field. How can I compare these dates in Laravel 4?

这不起作用。我阅读了文档,似乎您无法传递 Laravel MySQL 函数。 timestamp是一个日期时间字段。如何在 Laravel 4 中比较这些日期?

回答by duality_

The answer that user1977808 gave you is not good because MySQL can't use an index on the timestamp column, since it has to compute an output of the DATE_SUB function for every row. Avoid such queries, they have to process the entire table every time!

user1977808 给你的答案并不好,因为 MySQL 不能在时间戳列上使用索引,因为它必须为每一行计算 DATE_SUB 函数的输出。避免这样的查询,他们每次都必须处理整个表!

How about something like this:

这样的事情怎么样:

return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();

I put the >=in there because you said "a day or less old", so they must have timestamp that is later than yesterday.

我把它>=放在那里是因为你说“一天或更短”,所以他们的时间戳必须晚于昨天。

回答by afifahmi

Alternatively,

或者,

You can use Carbon APIthat bundle with Laravel.

您可以使用与 Laravel 捆绑在一起的Carbon API

ModelName::where( 'timestamp', '>=', Carbon::now() )->get();

Reference: http://laravel.com/docs/5.1/eloquent-mutators

参考:http: //laravel.com/docs/5.1/eloquent-mutators

回答by Jean-Philippe Murray

You could also use whereDate(), whereDay(), whereMonth()and whereYear(). In this case, whereDate()could be used as such, with Carbon's easy date functions:

你也可以使用whereDate()whereDay()whereMonth()whereYear()。在这种情况下,whereDate()可以使用 Carbon 的简单日期函数:

return MainContact::whereDate('dateField', '<', Carbon::now()->subDay())->get();

return MainContact::whereDate('dateField', '<', Carbon::now()->subDay())->get();

回答by socketman

return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();

回答by Cees van Egmond

You can also do a raw query by using:

您还可以使用以下方法进行原始查询:

$results = DB::query( 'query' );

You only don't the the model object back in the results var

你只是不要在结果变量中返回模型对象