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();
メソッドを少し調整できます。 scopeActive()
メソッドは、元のロジックwhereNowOrPast
に一致させることができます
$this->where('status', ArticleStatus::Published) ->whereNowOrPast('published_at');
とマークされた記事を見つけたい場合は、将来的にはPublished
メソッドを使用できます:whereFuture()
$this->where('status', ArticleStatus::Published) ->whereFuture('published_at');
およびor
バリアントが含まれます。
not
Laravel v11.42に追加されたすべての新しい相対日付メソッドについては、プルリクエスト#54408をチェックしてください。これらの方法は、
$this->whereAfterToday('published_at') ->orWhereBeforeToday('published_at');
以上がLaravel&#039;のクエリビルダーで相対日付ヘルパーを使用しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。