Laravel 选择特定年份的记录

问题描述 投票:0回答:4

我是 Laravel 新手,正在努力确定如何使用时间戳提供的created_at字段选择 2015 年创建的所有记录。

我使用的模型是博客:

$posts = Blog::latest()->get();

数据库中的日期示例:

2015-01-25 12:53:27

有人可以透露一些信息吗?

谢谢!

php laravel laravel-5.1
4个回答
35
投票

只是为了完成。 Laravel 有一个方法。

Blog::whereYear('created_at', 2017)->get();

参见 where 子句,小节

whereDate / whereMonth / whereDay / whereYear


9
投票

你可以这样做:

$posts = Blog::where( DB::raw('YEAR(created_at)'), '=', '2015' )->get();

在这里,您可以使用 YEAR 函数从created_at字段中获取年份,然后与您的日期进行比较。


2
投票

您可以在模型中使用范围方法。

型号:

class Blog extends Eloquent {
    public function scopePopular($query, $year)
    {
        return $query->where('year', '=', $year);
    }
}

用途:

$blog = Blog::popular(1999)->get();

1
投票

范围功能对我来说非常有效:

class Blog extends Eloquent {
public function scopeSeason($query,$year)
{
    return $query->whereYear('created_at', '=', $year);
}

}

用途:

$blog = Blog::where('status','active')->season(2021)->get();
© www.soinside.com 2019 - 2024. All rights reserved.