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

旧城冷巷雨未停 提交于 2019-12-20 17:42:28

问题


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

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

回答1:


There are date helpers available in the query builder:

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



回答2:


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

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

Read more about Carbon\Carbon getters documentation.



来源:https://stackoverflow.com/questions/32840698/how-to-select-year-and-month-from-the-created-at-attributes-of-database-table-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!