首页 >后端开发 >php教程 >使用Laravel中的相对日期助手

使用Laravel中的相对日期助手

Johnathan Smith
Johnathan Smith原创
2025-03-05 15:29:10349浏览

Using Relative Date Helpers in Laravel's Query Builder

Laravel 11.42 版本引入了一组实用的相对日期查询构建器方法,简化了日期相关的查询逻辑。虽然无需重构所有应用来使用这些方法,但它们确实为模型中的相对日期逻辑带来了更简洁易读的优势。让我们通过 Article 模型的示例来了解一下。

假设您有一个作用域用于获取具有特定状态的已发布文章,并且 published_at 日期必须等于或早于当前时间:

use Illuminate\Database\Eloquent\Builder;
use App\Models\Article;

public function scopeActive(): Article|Builder
{
    return $this->where('status', ArticleStatus::Published)
                ->where('published_at', '<=', now());
}

您可以将此作用域用于代码的其他地方,以将文章限制为仅活动文章。

Article::with('user', 'category', 'tags')
    ->active()
    ->orderByDesc('published_at')
    ->limit(20)
    ->get();

现在,使用 Laravel 11.42,我们可以对 scopeActive() 方法稍作调整,以使用相对日期方法。whereNowOrPast 方法可以匹配我们最初的逻辑:

$this->where('status', ArticleStatus::Published)
     ->whereNowOrPast('published_at');

如果要使用查询构建器查找标记为 Published 但仍在未来的文章,可以使用 whereFuture() 方法:

$this->where('status', ArticleStatus::Published)
     ->whereFuture('published_at');

如果要查找早于或晚于今天的日期的文章呢?新的相对日期辅助函数有 ornot 等变体:

$this->whereAfterToday('published_at')
     ->orWhereBeforeToday('published_at');

如需了解 Laravel v11.42 中添加的所有新的相对日期方法,请查看 Pull Request #54408。这些方法位于名为 BuildsWhereDateClauses 的新特性中。

以上是使用Laravel中的相对日期助手的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn