【问题标题】:Codeigniter blog: display post title in comments tableCodeigniter 博客:在评论表中显示帖子标题
【发布时间】:2018-05-19 16:32:35
【问题描述】:

我正在使用 Codeigniter 3.1.8 和 Bootstrap 4 开发一个博客应用程序

数据库中有一个posts表和一个cmets表。我已经在 Bootstrap 4 表中显示了所有 cmets。我想显示每个评论所属的帖子的 title,而不是帖子的 id

我的评论控制器:

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>

虽然&lt;?php echo $posts-&gt;id; ?&gt; 显示了我在视图中不需要的帖子ID,但 行会导致

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

缺少什么?

【问题讨论】:

    标签: php codeigniter codeigniter-3


    【解决方案1】:

    希望对您有所帮助:

    get_all_comments 方法应该是这样的:在选择中添加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>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 2021-01-18
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多