簡體   English   中英

Laravel 選擇特定年份的記錄

[英]Laravel Select records in specific year

我是 Laravel 的新手,正在努力確定如何使用時間戳提供的 created_at 字段選擇 2015 年創建的所有記錄。

我使用的模型是博客:

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

數據庫中的示例日期:

2015-01-25 12:53:27

有人能解釋一下嗎?

謝謝!

您可以這樣操作: $posts = Blog::where( DB::raw('YEAR(created_at)'), '=', '2015' )->get();

在這里,您可以使用YEAR函數從created_at字段中獲取年份,然后與您的日期進行比較。

只是為了完成。 有一個Laravel方法。

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

請參閱where子句其中小節whereDate / whereMonth / whereDay / whereYear

您可以在模型中使用范圍功能。 例如:

您的模型

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM