我是 Laravel 新手,正在努力确定如何使用时间戳提供的created_at字段选择 2015 年创建的所有记录。
我使用的模型是博客:
$posts = Blog::latest()->get();
数据库中的日期示例:
2015-01-25 12:53:27
有人可以透露一些信息吗?
谢谢!
只是为了完成。 Laravel 有一个方法。
Blog::whereYear('created_at', 2017)->get();
参见 where 子句,小节
whereDate / whereMonth / whereDay / whereYear
你可以这样做:
$posts = Blog::where( DB::raw('YEAR(created_at)'), '=', '2015' )->get();
在这里,您可以使用 YEAR 函数从created_at字段中获取年份,然后与您的日期进行比较。
您可以在模型中使用范围方法。
型号:
class Blog extends Eloquent {
public function scopePopular($query, $year)
{
return $query->where('year', '=', $year);
}
}
用途:
$blog = Blog::popular(1999)->get();
范围功能对我来说非常有效:
class Blog extends Eloquent {
public function scopeSeason($query,$year)
{
return $query->whereYear('created_at', '=', $year);
}
}
用途:
$blog = Blog::where('status','active')->season(2021)->get();