CodeIgniter - 加入用户、帖子、评论表

CodeIgniter - joining users, posts, comments tables

我在以下代码中加入了 3 个表:用户、post 和评论:

    public function join_user_post(){
        $this->db->select('
        posts.post_body,
        posts.date_created,
        users.username,
        users.user_image,   
        comments.comment_body,
        comments.date_created
    ');
        $this->db->from('posts');
        $this->db->join('users', 'users.id = posts.post_user_id ');
        $this->db->join('comments', 'comments.comment_post_id = posts.post_id ');
        $query = $this->db->get();
        return $query->result();
    }

然后通过控制器将此数组数据传递到主页视图:

<?php
class Home extends CI_Controller{

        public function index(){
            $this->load->model('user_model');
            $data['posts'] = $this->user_model->join_user_post();
            $this->load->view("user/homepage",$data);
        }
}
?>

在主页视图中,我试图用用户名和用户图像回显 post,然后遍历每个 post 的评论并将其回显

    <body>
    <?php include 'navbar.php';?>

    <?php foreach($posts as $post): ?>
        <div>
            <img src="<?php echo $post->user_image ?><br>">
            <?php echo $post->username ?><br>
            <?php echo $post->post_body ?><br>
            <?php echo $post->date_created ?><br>

            <?php foreach($posts as $post): ?>
                <?php echo $post->comment_body ?><br>
                <?php echo $post->date_created ?><br>


            <?php endforeach; ?>

        </div>

    <?php endforeach; ?>
    </body> 

但我宁愿获取每个 post 上的所有评论,而不是获取与特定 post id 相关的评论,foreach 循环遍历所有评论并在每个 [=21] 上回显它们=],如果我删除 foreach 循环,它只会在每个 post 处回显一条评论 我应该怎么做才能解决这个问题?

问题是当您加入带有评论的 post 时,它 return 许多评论记录具有相同的 post。您可以先在控制器中稍微修改一下,以存储每个 post 以及属于它的评论:

function index()
{
    $this->load->model('user_model');
    $comments = $this->user_model->join_user_post();
    $posts = array();
    foreach ($comments as $comment) {
        if (array_key_exists($comment->post_id, $posts)) {
            $posts[$comment->post_id]['comments'][] = $comment;
        } else {
            $posts[$comment->post_id]['post_body'] = $comment->post_body;
            $posts[$comment->post_id]['username'] = $comment->username;
            $posts[$comment->post_id]['date_created'] = $comment->date_created;
            $posts[$comment->post_id]['user_image'] = $comment->user_image;
            $posts[$comment->post_id]['comments'][] = $comment;
        }
    }
    $data['posts'] = $posts;
    $this->load->view("user/homepage", $data);
}

在您看来:

<div>
    <img src="<?php echo $post['user_image'] ?><br>">
    <?php echo $post['username'] ?><br>
    <?php echo $post['post_body'] ?><br>
    <?php echo $post['date_created'] ?><br>

    <?php foreach ($posts['comments'] as $comment) : ?>
        <?php echo $comment->comment_body ?><br>
        <?php echo $comment->date_created ?><br>
    <?php endforeach; ?>

</div>