You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codeigniter博客:如何在评论表格中显示对应文章标题?

嘿,这个问题我太熟了——你遇到的Undefined index: title错误,核心原因就是你的评论查询没有关联posts表,根本没把文章title数据拉出来。让我一步步帮你修复:

1. 先修改评论模型(比如Comment_model.php)

你需要在查询评论的时候,通过post_id关联posts表,把文章标题一起查出来。替换你当前的获取所有评论的方法:

public function get_all_comments()
{
    // 选择评论表的所有字段,同时拉取对应文章的title,并命名为post_title避免字段冲突
    $this->db->select('comments.*, posts.title as post_title');
    $this->db->from('comments');
    // 用左连接保证即使某篇文章被删除,对应的评论依然能显示
    $this->db->join('posts', 'posts.id = comments.post_id', 'left');
    
    // 如果有其他筛选条件(比如只显示已审核评论),可以在这里继续加where
    // $this->db->where('comments.status', 1);
    
    $query = $this->db->get();
    return $query->result_array();
}

2. 确保控制器正确传递数据

你的控制器应该是调用模型获取评论数据,然后传给视图,这一步如果之前没问题就不用改,比如:

public function index()
{
    $this->load->model('Comment_model');
    $data['comments'] = $this->Comment_model->get_all_comments();
    $this->load->view('comments_list', $data);
}

3. 调整视图显示标题

之前你用<?php echo $posts['title']; ?>肯定会报错,因为视图里循环的是评论数据,而且我们已经把文章标题命名为post_title了。修改Bootstrap表格里的对应列:

<?php foreach($comments as $comment): ?>
<tr>
    <td><?php echo $comment['id']; ?></td>
    <!-- 这里用关联查询出来的post_title -->
    <td><?php echo $comment['post_title']; ?></td>
    <td><?php echo $comment['author']; ?></td>
    <td><?php echo $comment['content']; ?></td>
    <!-- 其他评论字段 -->
</tr>
<?php endforeach; ?>

为啥之前会报错?

简单说:你之前的查询只从comments表里拿数据,comments表只有post_id没有title,所以视图里根本找不到title这个索引。关联查询后,每一条评论数据里就带上了对应文章的标题,自然就能正常显示了。

内容的提问来源于stack exchange,提问作者Razvan Zamfir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:02:35