laravel - Laravel 查询比当前时间更近的日期
问题描述
我正在使用 Laravel 雄辩的模型。我想添加一个查询条件where start_time later than now
。
例如:
Model::whereAfterNow('start_time')->all()
你能帮助我吗??
解决方案
看起来您需要一个查询范围(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();
推荐阅读
- stata - 如何在Stata中转置变量的部分?
- java - 如何使用 ByteBuddy 读取 Java 类方法注解
- python - Django 每天午夜在后台更新一个静态 csv 文件
- python - 如何使用 pandas 找到每个主成分的前三个特征?
- javascript - 等待整个同步循环的 Javascript
- python - 可执行的 Python 脚本不会从 crontab 运行
- python - Python 请求返回 200 状态码但没有做我想做的事
- r - ggplot:一张图上有两条线,日期中断(y轴)
- haskell - 实例化某些对象(Haskell)
- java - 片段视图返回后执行的 Firebase 查询