gpt4 book ai didi

php - Laravel 按年份和月份生成存档帖子

转载 作者:行者123 更新时间:2023-11-29 21:30:51 24 4
gpt4 key购买 nike

我现在将使用 Laravel 4.2 的归档系统(列表)年份和月份恢复我的文章。

我每年和每月都能毫无问题地检索我的元素(见下文)

这是我使用查询生成器 Laravel 的 Controller

public function index(){
$post_links = DB::table('posts')
->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count'))
->groupBy('year')
->groupBy('month')
->orderBy('year', 'desc')
->orderBy('month', 'desc')
->get();

return View::make('home.index')->with(array(
'post_links'=>$post_links,

));
}

还有我的看法

 <ul id="show-year">
@foreach($post_links as $link)
{{--{{dd($link)}}--}}
{{--Show year--}}
<li>
<a title="" href="#">
<span>
<strong>{{$link->year}}</strong></a>&nbsp;<span class="post-count">{{$link->post_count}}</span><i class="fa fa-arrow-right"></i>
</span>
</li>
</a>
{{--show month--}}
<ul id="show-month">
<li class="month-content">
<a href="">
<span>
<strong>{{$link->month_name}}</strong>
</span>
</a>
</li>
</ul>
</li>
@endforeach
</ul>

我恢复了我的数据数年和数月,但它以这种方式每个月为她增加了一年

2015 ( 21 )- 五月 (2)- 四月 (3)- 三月 (5)- 二月 (1)- 一月 (10)2016 (10)- 十二月 (6)- 十一月(4)

我不明白为什么它不将我分组在同一年,而是每次为每个月生成一个新的年份条目。

感谢您的帮助。

最佳答案

为了在某种导航面板中生成链接,您可以在数据库端完成大部分处理,而不是使用这样的查询来获取所有博客文章记录

SELECT YEAR(created_at) year,
MONTH(created_at) month,
MONTHNAME(created_at) month_name,
COUNT(*) post_count
FROM post
GROUP BY year, MONTH(created_at)
ORDER BY year DESC, month DESC;

输出:

| YEAR | MONTH | MONTH_NAME | POST_COUNT |
------------------------------------------
| 2013 | 5 | May | 5 |
| 2013 | 4 | April | 3 |
| 2013 | 3 | March | 4 |
| 2013 | 2 | February | 3 |
| 2013 | 1 | January | 2 |
| 2012 | 12 | December | 2 |
| 2012 | 11 | November | 3 |

类似这样的代码

  $links = DB::table('post')
->select(DB::raw('YEAR(created_at) year, MONTH(created_at) month, MONTHNAME(created_at) month_name, COUNT(*) post_count'))
->groupBy('year')
->groupBy('month')
->orderBy('yea`enter code here`r', 'desc')
->orderBy('month', 'desc')
->get();

原始解决方案是 here

关于php - Laravel 按年份和月份生成存档帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35279386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com