php - Codeigniter 根据 View 中的 id 在 View 中显示来自 2 个不同表的数据

标签 php mysql sql codeigniter

我会尽力尽可能清楚地解释这一点:

这是我的爱好 Controller 函数,它获取我拥有的关于爱好帖子的所有数据,并将这些数据显示在 group_homepage View 中。

public function group_homepage($hobby_id){
    $this->load->model('model_posts');

    $data['posts'] = $this->model_posts->get_all_posts($hobby_id);

    $this->load->view('group_homepage',$data);

}

现在的问题是,对于我在 View 中显示的每个帖子,我还想显示用户的个人资料图片和姓名(在我的数据库的 USER 表中找到)以及与该特定帖子相关的所有评论(在我的数据库的 COMMENT 表中找到)。

我的group_homepage看起来像这样:

<ul id='news_feed'>
   <?php
    foreach($posts as $post){
            echo "<li>";
            echo "<div class='left_post'>";
            echo "<a href='".base_url()."/index.php/login/open_profile/".$user_id."'>";
            echo"<img src='".base_url()."/uploads/".**USER'S PHOTO**."' alt='profile picture'>";
            echo "</a>";
            echo "</div>";

            echo "<div class='right_post'>";
            echo $post->message_text;
            echo " <p class='post_details'>written by <span>";
            echo **USER'S NAME**;
            echo "</span>, ";
            $db = $post->timestamp;
            $timestamp = strtotime($db);
            echo date("d-m-Y, G:i", $timestamp);
            **DISPLAY ALL POST'S COMMENTS**
            echo "</p></div></li>";
    }

?>
</ul>

您知道如何根据每个帖子检索此信息并将其与我已有的有关该帖子的其他信息一起显示吗?

模型函数非常简单:

public function get_all_posts($hobby_id){
            $this->db->where('group_id',$hobby_id);
            $query = $this->db->get('post');
            return $query->result();
        }

我还应该提到,我的 POST 表具有以下字段:post_id、user_id、timestamp、message_text、group_id 和 Likes

最佳答案

开始之前,请先阅读本用户指南 codeigniter Active Record Class ,在你的函数中

public function get_all_posts($hobby_id){
    $this->db->where('group_id',$hobby_id);
    $this->db->join('users', 'users.id = post.user_id'); //join with users table
    $this->db->join('comments', 'comments.user_id = post.user_id'); //join with comments table
    $query = $this->db->get('post');
    return $query->result();
}

现在您将拥有所有数据,包括用户的个人资料和评论,进行循环并根据您的要求显示。例如,将名称和图片打印到 View

 echo $post->name; 
 echo $post->picture; //you have to use image tag here to display user's picture.

关于php - Codeigniter 根据 View 中的 id 在 View 中显示来自 2 个不同表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23456120/

相关文章:

c++ - 将 std::wstring 转换为 SQLWCHAR *

sql - 用户输入作为 Oracle SQL 中的日期

php - Doctrine2 级联实体创建

mysql游标使用动态限制

php - 如何计算图像中的像素数(php)

php - 准备好的语句mysql/php的语法错误

mysql - 查找日期范围内每天有多少单位可用

sql - ScalaQuery 多对多

php - 在 php 和 MySQL 中匹配和返回行

php - 通配符 mysql LIKE 或 IN 数组值问题