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');
如果要查找早於或晚於今天的日期的文章呢?新的相對日期輔助函數有 or
和 not
等變體:
$this->whereAfterToday('published_at') ->orWhereBeforeToday('published_at');
如需了解 Laravel v11.42 中添加的所有新的相對日期方法,請查看 Pull Request #54408。這些方法位於名為 BuildsWhereDateClauses
的新特性中。
以上是使用Laravel中的相對日期助手的詳細內容。更多資訊請關注PHP中文網其他相關文章!