代码之家  ›  专栏  ›  技术社区  ›  Razvan Zamfir

CodeIgniter博客:在评论表中显示文章标题

  •  -2
  • Razvan Zamfir  · 技术社区  · 7 年前

    我正在做一个 博客应用程序 在codeigner 3.1.8和bootstrap 4中。

    有一个 帖子 表和A 评论 数据库中的表。我已经在bootstrap 4表中显示了所有注释。我想展示 标题 每个评论所属的,而不是帖子的 身份证件 :

    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');
      }
    }
    

    注释\模型 我拥有的型号:

    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 回复  |  直到 7 年前
        1
  •  1
  •   Pradeep    7 年前

    希望这对您有所帮助:

    get_all_comments 方法应如下所示: 添加 posts.title 在Select also中

    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>