php 如何从laravel 5.1中数据库表的created_at属性中选择年和月?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32840698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:14:32  来源:igfitidea点击:

How to select year and month from the created_at attributes of database table in laravel 5.1?

phpsqllaraveleloquentlaravel-5.1

提问by Pawan Dongol

My problem is that I want to get data form the database table from the created_atattributes as per year and month only. The code I have tried is:

我的问题是我只想从created_at每年和每月的属性中获取数据库表中的数据。我试过的代码是:

$post= Mjblog::select(DB::raw('YEAR(created_at) year, MONTH(created_at) month'));
$posts_by_y_m = $post->where('created_at',$post)->get();

回答by Martin Bean

There are date helpers available in the query builder:

查询构建器中有可用的日期助手:

$post = Mjblog::whereYear('created_at', '=', $year)
              ->whereMonth('created_at', '=', $month)
              ->get();

回答by sebdesign

If you want to get the year and month from a single instance of Mjblogyou can access them like this:

如果您想从单个实例中获取年份和月份,Mjblog您可以像这样访问它们:

$year = $post->created_at->year;
$month = $post->created_at->month;

Read more about Carbon\Carbongetters documentation.

阅读有关Carbon\Carbongetter 文档的更多信息。