CodeIgniter - order my 'posts' by month?

…衆ロ難τιáo~ 提交于 2020-01-07 05:05:33

问题


In my website I'd like to create an 'archive' list to categorise my posts.

My posts table is set up like so: id | post_title | post | pubdate | year | month

Currently this model function pulls the posts:

function getNews(){
     $data = array();
     $this->db->order_by("id", "desc");
     $Q = $this->db->get('posts');
     if ($Q->num_rows() > 0){
       foreach ($Q->result_array() as $row){
         $data[] = $row;
       }
    }
    $Q->free_result();  
    return $data;
}   

However, is it possible I can create a list like the following?

July (12)

June (5)

May (2)

So it lists the month and the number of posts within that month?

All my attempts thus far have ended in frustration and tears. Any help would be greatly appreciated.


回答1:


Try this one

SELECT  `year`,`month`,(SELECT COUNT(id) FROM `posts` WHERE `month` =p.`month`) AS c
FROM `posts` p  GROUP BY p.`month` ORDER BY `month`

function getNews(){
 $data = array();

 $Q = $this->db->query('SELECT `year`,`month`,(SELECT COUNT(id) FROM `posts` WHERE `month`=p.`month`) AS c FROM `posts` p  GROUP BY p.`month`ORDER BY `month`');
 if ($Q->num_rows() > 0){
   foreach ($Q->result_array() as $row){
     $data[] = $row;
   }
}
$Q->free_result();  
return $data;
}



回答2:


This is not codeigniter related but i'll answer you anyway.

use SELECT Count(*) then order by 'month', write a query and run it using this

http://ellislab.com/codeigniter/user-guide/database/queries.html



来源:https://stackoverflow.com/questions/17073231/codeigniter-order-my-posts-by-month

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