CodeIgniter 3博客Bug:文章ID被替换为分类ID
解决CodeIgniter分类页文章链接指向分类ID而非文章ID的问题
看起来你遇到的问题是分类页下的所有文章详情链接都指向了分类ID(比如http://localhost/ciblog/posts/post/1),而不是对应的文章ID——这大概率是视图里构建链接时用错了参数,咱们一步步来排查解决:
1. 检查视图中的链接代码(最可能的问题根源)
你需要确认在分类页的视图文件(比如views/posts/category.php)里,生成文章详情链接时是否误用了分类ID,而不是文章ID。
错误示例(用了分类ID):
<!-- 错误:这里误用了分类ID变量,比如$category_id --> <a href="<?php echo site_url('posts/post/'.$category_id); ?>">查看文章</a>
正确写法(用文章自身的ID):
<!-- 正确:遍历文章列表时,调用每个文章的id字段 --> <?php foreach ($posts as $post): ?> <h2><a href="<?php echo site_url('posts/post/'.$post['id']); ?>"><?php echo $post['title']; ?></a></h2> <!-- 文章摘要、发布时间等其他内容 --> <?php endforeach; ?>
2. 确认模型查询是否正确返回文章ID
你的get_posts_by_category方法可能存在字段缺失或别名冲突的问题,比如关联分类表时,如果两张表都有id字段,需要明确指定文章的ID:
补全并修正后的模型方法示例:
public function get_posts_by_category($id, $limit, $offset) { // 明确选择posts表的所有字段,避免和categories表的id字段冲突 $this->db->select('posts.*, categories.name as category_name'); $this->db->from('posts'); $this->db->join('categories', 'posts.category_id = categories.id'); $this->db->where('categories.id', $id); $this->db->order_by('posts.id', 'DESC'); $this->db->limit($limit, $offset); // 你之前的代码里写的是limi,应该是limit return $this->db->get()->result_array(); }
如果查询时没有指定posts.id,可能会导致返回的id是分类表的ID,这也会造成链接错误。
3. 验证控制器是否正确传递文章数据
确保你的分类页控制器方法(比如Posts控制器的category方法)已经把查询到的文章列表正确传递给视图:
控制器示例:
public function category($id) { $per_page = 5; $offset = $this->uri->segment(4) ? $this->uri->segment(4) : 0; // 获取分类下的文章列表 $data['posts'] = $this->posts_model->get_posts_by_category($id, $per_page, $offset); // 获取当前分类信息(可选) $data['current_category'] = $this->categories_model->get_category($id); $this->load->view('templates/header'); $this->load->view('posts/category', $data); $this->load->view('templates/footer'); }
总结
最常见的原因就是视图里构建链接时用了分类ID变量,而不是遍历文章列表时每个文章的id字段。先检查视图代码,再确认模型查询是否正确返回文章ID,基本就能解决这个问题。
内容的提问来源于stack exchange,提问作者Razvan Zamfir
相关产品推荐
相关产品推荐

