首页 > 解决方案 > Laravel 查询比当前时间更近的日期

问题描述

我正在使用 Laravel 雄辩的模型。我想添加一个查询条件where start_time later than now

例如:

Model::whereAfterNow('start_time')->all()

你能帮助我吗??

标签: laraveleloquent

解决方案


看起来您需要一个查询范围(https://laravel.com/docs/5.6/eloquent#local-scopes)。

假设“start_time”是一个模型属性(数据库字段),包含时间的某种表示,并且您想要一个返回所有模型的范围where 'start_time' later than now......

如何构建代码取决于日期在数据库中存储的格式。

例如,如果您使用的是纪元时间戳,那么在您的 Model.php 中:

public function scopewhereAfterNow($query)
{
    return $query->where('start_time', '>', \Carbon\Carbon::now()->timestamp);
}

或者你可以使用 DB 门面:

public function scopewhereAfterNow($query)
{
    return $query->where('start_time', '>', DB::raw('unix_timestamp(NOW())'));
}

您可能会这样称呼: $results = Model::whereAfterNow()->get();


推荐阅读