i want to group posts or news by year and month how i can do such thing
this format for example
2019 apr [post 1, post 2] may [post 1, post 2]
2018 apr [post 1, post 2] may [post 1, post 2]
You can use the combination of laravel eloquent and Carbon
use Carbon\Carbon;
$news = New::select('id', 'title', 'created_at')
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y');
});
By default we can make group by only with primary keys. if you want to add group by with other attributes you have to enable ONLY_FULL_GROUP_BY
sql mode by adding the below code on config/database.php
'mysql' => [
.....
'modes' => [
'ONLY_FULL_GROUP_BY',
],
recommended modes:
'STRICT_ALL_TABLES',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_ZERO_DATE',
'NO_ZERO_IN_DATE',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION',
once you enabled the mode then you can try the query here which returns the result group by year and month.
DB::table('posts')->groupBy([DB::raw("MONTH(posts_date)"), DB::raw("YEAR(posts_date)")])
->get();
I hope this will help you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.