You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 7 Eloquent如何优雅比较值为0000-00-00 00:00:00的日期时间?

在Laravel 7 Eloquent中优雅处理0000-00-00 00:00:00日期的查询

自定义局部作用域

最优雅的方式是给Person模型添加自定义局部作用域,把判断died_at为0000-00-00 00:00:00的逻辑封装起来,方便复用:

// app/Models/Person.php
public function scopeWhereNotDied($query)
{
    return $query->where('died_at', '0000-00-00 00:00:00');
}

// 若需查询"已去世"的记录,可补充对应作用域
public function scopeWhereDied($query)
{
    return $query->where('died_at', '<>', '0000-00-00 00:00:00');
}

使用时非常简洁:

// 查询未去世的人员
$alivePersons = Person::whereNotDied()->get();

// 查询已去世的人员
$deadPersons = Person::whereDied()->get();

模型访问器辅助实例判断(可选)

如果需要在模型实例层面判断该日期是否为无效值,可以添加访问器:

// app/Models/Person.php
public function getIsAliveAttribute()
{
    return $this->died_at === '0000-00-00 00:00:00';
}

使用时直接访问属性:

$person = Person::find(1);
if ($person->is_alive) {
    // 执行对应逻辑
}

补充说明

whereNull('died_at')不生效的原因是数据库中该字段实际存储的是字符串0000-00-00 00:00:00而非NULL值。如果后续有机会,建议将这些无效日期更新为NULL,并调整表结构允许该字段为NULL,这样就能直接使用whereNull和whereNotNull,更贴合Laravel的惯用写法。

内容的提问来源于stack exchange,提问作者JohnSmith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:43:12