Laravel 4+ 为您提供了以下方法:whereDay()
, whereMonth()
, whereYear()
(#3946 https://github.com/laravel/framework/pull/3946) and whereDate()
(#6879 https://github.com/laravel/framework/pull/6879).
他们执行 SQLDATE()
为您工作,并管理 SQLite 的差异。
您的结果可以这样实现:
->whereDate('date', '<=', '2014-07-10')
有关更多示例,请参阅第一条消息#3946 https://github.com/laravel/framework/pull/3946和这个Laravel 每日文章 http://laraveldaily.com/eloquent-date-filtering-wheredate-and-other-methods/.
Update:尽管上述方法很方便,但正如 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'))->modify('+1 day')->format('Y-m-d');
->where('date', '<', $dayAfter)
Notes:
- 23:59:59 还可以(目前),因为精度为 1 秒,但请看一下这篇文章:23:59:59 还不是一天的结束。不完全是! http://code.openark.org/blog/mysql/235959-is-not-the-end-of-the-day-no-really
- 请记住“零日期”情况(“0000-00-00 00:00:00”)。尽管应该避免这些“零日期”,但它们是许多问题的根源。如果需要,最好将该字段设置为空。