首頁 >後端開發 >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