Laravel雄辩比较日期从datetime字段 [英] Laravel Eloquent compare date from datetime field

查看:1485
本文介绍了Laravel雄辩比较日期从datetime字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过表达式从表格中获取所有行:

  table.date< = 2014-07 -10 

但是如果列包含datetime,我们假设:

  2014-07-10 12:00:00 

但是如果我这样做:

  where('date','< =',$ date)

它不会得到该行。



我猜这是因为$ date = 2014-07-10这使得MySQL假定是2014-07-10 00:00:00。



在常规的MySQL我只会做

 其中DATE(日期)< = $ date 
pre>

使用拉拉维尔的口才是什么等同的?

解决方案

Laravel 4+为您提供以下方法: whereDay() whereMonth() whereYear )#3946 )和 whereDate()#6879 )。



他们请执行SQL DATE()为您工作,并管理SQLite的差异。



您的结果可以实现如下:

   - > whereDate('date','< =','2014-07-10') 

有关更多示例,请参阅#3946 和此 Laravel Daily文章





更新:虽然上述方法很方便,如Arth所述,它是低效的大数据集,因为 DATE() SQL函数必须应用于每个记录,从而丢弃可能的索引。



与字符串进行比较的值,以下是进行比较的一些方法(但请阅读以下注释):

   - > where('date','< =','2014-07-10 23:59:59')

- > where('date','& ,'2014-07-11')

//'2014-07-11'
$ dayAfter =(new DateTime('2014-07-10')) - >修改('+1天') - >格式('Ym-d');

- > where('date','<',$ dayAfter)

注意:




  • 23:59:59由于1秒的精度,因此可以(现在)看看这篇文章: 23:59:59不是一天的结束。不,真的!

  • 请记住零日的情况(0000-00-00 00:00:00)。虽然这些零日应该避免,但却是这么多问题的根源。如果需要,更好地使该字段为空。


I want to get all the rows from a table through an expression:

table.date <= 2014-07-10

But if the column contains a datetime let's say:

2014-07-10 12:00:00

But if I do:

where('date', '<=', $date)

it won't get the row.

I guess this is because $date = 2014-07-10 which makes MySQL assume that it is 2014-07-10 00:00:00.

In regular MySQL I would just do

where DATE(date) <= $date

What would be the equivalent using Laravel's Eloquent?

解决方案

Laravel 4+ offers you these methods: whereDay(), whereMonth(), whereYear() (#3946) and whereDate() (#6879).

They do the SQL DATE() work for you, and manage the differences of SQLite.

Your result can be achieved as so:

->whereDate('date', '<=', '2014-07-10')

For more examples, see first message of #3946 and this Laravel Daily article.


Update: Though the above method is convenient, as noted by Arth it is inefficient on large datasets, because the DATE() SQL function has to be applied on each record, thus discarding the possible index.

The values being compared like strings, here are some ways to make the comparison (but please read notes below):

->where('date', '<=', '2014-07-10 23:59:59')

->where('date', '<', '2014-07-11')

// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');

->where('date', '<', $dayAfter)

Notes:

  • 23:59:59 is okay (for now) because of the 1-second precision, but have a look at this article: 23:59:59 is not the end of the day. No, really!
  • Keep in mind the "zero date" case ("0000-00-00 00:00:00"). Though, these "zero dates" should be avoided, they are source of so many problems. Better make the field nullable if needed.

这篇关于Laravel雄辩比较日期从datetime字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆