在 Laravel 查询构造器中使用相对日期 Helper
随着 Laravel 11.42 的发布,我们现在可以使用访问日期的相对查询构建器方法。虽然你不需要重构所有应用来使用这些方法,但它们为模型中的相对日期逻辑添加了一个很好的可读性。
假设你有一个 scope 用以获取包含某个指定状态的文章,published_at
日期必须小于或者等于 now()
:
use Illuminate\Database\Eloquent\Builder;
use App\Models\Article;
public function scopeActive(): Article|Builder
{
return $this->where('status', ArticleStatus::Published)
->where('published_at', '<=', now());
}
你可以在代码的其他地方使用此 scope 来约束文章为仅限激活:
Article::with('user', 'category', 'tags')
->active()
->orderByDesc('published_at')
->limit(20)
->get();
使用 Laravel 11.42,我们可以在 scopeActive()
方法来做微调使用相对日期方法。我们希望 whereNowOrPast
匹配我们的原来的逻辑:
$this->where('status', ArticleStatus::Published)
- ->where('published_at', '<=', now());
+ ->whereNowOrPast('published_at');:
如果我们想使用查询构造器来查找标记为已发布(published),不过仍在未来的文章,我们可以使用 whereFuture()
方法:
$this->where('status', ArticleStatus::Published)
->whereFuture('published_at');
如果我们想要查找今天日期之前或者之后的文章呢?新的相对日期 helper 也有如 or
和 not
那样的变体:
$this->whereAfterToday('published_at')
->orWhereBeforeToday('published_at');