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

2023-10-31php开发问题
57

本文介绍了Laravel Eloquent 比较日期时间字段中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

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

但如果我这样做:

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

它不会得到该行.

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

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

在常规 MySQL 中我会这样做

In regular MySQL I would just do

where DATE(date) <= $date

使用 Laravel 的 Eloquent 的等价物是什么?

What would be the equivalent using Laravel's Eloquent?

推荐答案

Laravel 4+ 为你提供了这些方法:whereDay(), whereMonth(), whereYear() (#3946) 和 whereDate() (#6879).

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

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

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')

更多例子请看#3946的第一条消息和这个Laravel Daily 文章.

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


更新: 虽然上述方法很方便,但正如 Arth 所说,它在大型数据集上效率低下,因为必须对每条记录应用 DATE() SQL 函数,因此丢弃可能的索引.


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.

以下是一些进行比较的方法(但请阅读下面的注释):

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)

注意事项:

  • 23:59:59 可以(暂时)因为 1 秒的精度,但请看这篇文章:23:59:59 不是一天的结束.不,真的!
  • 请记住零日期"情况(0000-00-00 00:00:00").尽管应该避免这些零日期",但它们是许多问题的根源.如果需要,最好使该字段可以为空.

这篇关于Laravel Eloquent 比较日期时间字段中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17