Laravel Eloquent 比较日期时间字段中的日期

2024-01-06

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

table.date <= 2014-07-10

但如果该列包含日期时间,我们可以说:

2014-07-10 12:00:00

但如果我这样做:

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

它不会得到该行。

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

在常规 MySQL 中我会这样做

where DATE(date) <= $date

使用 Laravel 的 Eloquent 相当于什么?


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”)。尽管应该避免这些“零日期”,但它们是许多问题的根源。如果需要,最好将该字段设置为空。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel Eloquent 比较日期时间字段中的日期 的相关文章

随机推荐