Codeigniter博客:在评论表中显示帖子标题

时间:2018-05-19 16:32:36

标签: php codeigniter codeigniter-3

我正在使用Codeigniter 3.1.8和Bootstrap 4中的博客应用程序

数据库中有个帖子表和评论表。我在Bootstrap 4表中显示了所有注释。我想显示每个评论所属帖子的标题,而不是帖子 id

enter image description here

我的评论控制器:

class Comments extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
    $this->load->model('Static_model');
    $this->load->model('Posts_model');
    $this->load->model('Categories_model');
    $this->load->model('Comments_model');
  }

  public function index() {
    $data = $this->Static_model->get_static_data();
    $data['categories'] = $this->Categories_model->get_categories();
    $data['number_of_categories'] = $this->Categories_model->get_num_rows();
    $data['posts'] = $this->Posts_model->get_all_posts();
    $data['number_of_posts'] = $this->Posts_model->get_num_rows();
    $data['comments'] = $this->Comments_model->get_all_comments();

    $this->load->view('partials/header', $data);
    $this->load->view('dashboard/comments');
    $this->load->view('partials/footer');
  }
}

Comments_model 模型中,我有:

public function get_all_comments(){
    $this->db->select('comments.*');
    $this->db->order_by('comments.id', 'DESC');
    //$this->db->limit($limit, $offset);
    $this->db->join('posts', 'posts.id = comments.post_id');        
    $query = $this->db->get('comments');
    return $query->result();
}

在视图中:

<tbody>
  <?php foreach ($comments as $index => $comment): ?>
  <tr id="<?php echo $comment->id; ?>">
    <td><?php echo $index + 1; ?></td>
    <td class="w-25"><?php echo $comment->comment; ?></td>
    <td><?php echo $comment->name; ?></td>
    <td><?php echo $posts['title']; ?></td>
    <td><?php echo nice_date($comment->created_at, 'D, M d, Y'); ?></td>
    <td>Aproved</td>
    <td></td>
  </tr>
  <?php endforeach ?>
</tbody>

虽然<?php echo $posts->id; ?>显示了帖子ID,但在视图中我不需要, 行会产生

  

消息:未定义的索引:标题错误。

缺少什么?

1 个答案:

答案 0 :(得分:1)

希望这会对您有所帮助:

get_all_comments方法应该是这样的:在select中添加posts.title

public function get_all_comments()
{
   $this->db->select('comments.*,posts.title as post_title');
   $this->db->order_by('comments.id', 'DESC');
   //$this->db->limit($limit, $offset);
   $this->db->join('posts', 'posts.id = comments.post_id');        
   $query = $this->db->get('comments');
   return $query->result();
}

替换它

<td><?php echo $posts['title']; ?></td>

<td><?php echo $comment->post_title; ?></td>
相关问题