Laravel查询日期比当前时间最近的日期

Dav*_*vit 2 laravel eloquent

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

例如:

Model::whereAfterNow('start_time')->all()
Run Code Online (Sandbox Code Playgroud)

你能帮助我吗??

Ben*_*ice 5

看起来您需要一个查询范围(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);
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用数据库外观:

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

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