且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel雄辩比较日期从datetime字段

更新时间:2023-01-29 10:38:03

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.