我正在使用Codeigniter 3.1.8中的基本博客应用程序。
通过此方法从 Posts_model 模型按类别过滤帖子:
public function get_posts_by_category($id, $limit, $offset) {
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.cat_id');
$query = $this->db->get_where('posts', array('cat_id' => $id));
return $query->result();
}
在类别控制器中,我有:
public function posts($id) {
$this->load->library('pagination');
$config = [
'base_url' => base_url('/categories/posts/' . $id),
'page_query_string' => TRUE,
'query_string_segment' => 'page',
'display_pages' => TRUE,
'use_page_numbers' => TRUE,
'per_page' => 12,
'total_rows' => $this->Posts_model->get_num_rows_by_category($id),
'uri_segment' => 3,
'first_link' => '«',
'first_tag_open' => '<li>',
'first_tag_close' => '</li>',
'last_link' => '»',
'last_tag_open' => '<li>',
'last_tag_close' => '</li>',
'full_tag_open' => '<ul class="pagination">',
'full_tag_close' => '</ul>',
'next_link' => '›',
'next_tag_open' => '<li>',
'next_tag_close' => '</li>',
'prev_link' => '‹',
'prev_tag_open' => '<li>',
'prev_tag_close' => '</li>',
'num_tag_open' => '<li>',
'num_tag_close' => '</li>',
'cur_tag_open' => '<li class="active"><span>',
'cur_tag_close' => '</span></li>'
];
if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
$_GET[$config['query_string_segment']] = 1;
}
$limit = $config['per_page'];
$offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;
$this->pagination->initialize($config);
$data['categories'] = $this->Categories_model->get_categories();
$data['category_name'] = $this->Categories_model->get_category($id)->name;
$data['posts'] = $this->Posts_model->get_posts_by_category($id, $limit, $offset);
$this->load->view('partials/header', $data);
$this->load->view('categories/posts');
$this->load->view('partials/footer');
}
问题:每当我显示一个类别时,即使我点击了不同的分页项目并且网址显示为http://localhost/blog/categories/posts/1
,我也只能在第一页上看到该帖子:http://localhost/blog/categories/posts/1?page=2
上。
我的错误在哪里?
答案 0 :(得分:1)
你没有在模型的get_posts_by_category
方法中添加限制。试试这个
public function get_posts_by_category($id, $limit, $offset) {
$this->db->order_by('posts.id', 'DESC');
//you misssed this line
$this->db->limit($limit, $offset);
$this->db->join('categories', 'categories.id = posts.cat_id');
$query = $this->db->get_where('posts', array('cat_id' => $id));
return $query->result();
}