获取CodeIgniter中论坛主页中每个类别的最新主题

I am creating a simple forum using the CodeIgniter.

I want to get latest topic for each category in Forum Home Page. What i want is like so- Forum Index

It's OK for a category page to get latest topic, but I can't get for Home Page

My Controller for Home Page Category List -

class Category extends CI_Controller {

    public function index()
    {
        $this->load->model('Category_model');

        $data['categories'] = $this->Category_model->get_all_categories();

        $this->load->view('forums/index', $data);
    }
}

My Model -

class Category_model extends CI_Model {
    function get_all_categories()
    {
        $get_categories = $this->db->get('categories');
        return $get_categories->result_array();
    }

}

DB Structure-

Topics

  • topic_id
  • topic_title
  • topic_content
  • topic_cat_id

Categories

  • cat_id
  • cat_name
  • cat_description

You can try this, Hope it helps:

function get_all_categories()
{
    $data           = array();
    $get_categories = $this->db->get('categories');
    $cat            = $get_categories->result_array();
    foreach( $cat as $key=>$each ){
        $rs = $this->db->where('topic_cat_id', $each['cat_id'])->oreder_by('topic_id', 'desc')->get('Topics', 1)->row_array();
        $data[$key]['cat']  = $each;
        $data[$key]['top']  = $rs;
    }
    echo "<pre>";print_r( $data );
    return $data;
}

To get latest topic for each category you can try this one:

$this->db->select_max('topic_id');
$this->db->select('topic_title,topic_content,topic_cat_id');
$this->db->group_by("topic_cat_id");
$this->db->order_by("topic_id", "desc");//ordering direction for topic id
$get_categories = $this->db->get('topics');
$result = $get_categories->result_array();