[eluser]ddbt[/eluser]
Dear community..
while working on my little CI blog project I got stuck at the point where I want my post metadata (post author, post date, post time and number of comments) to show throughout the foreach loop in the view file. I managed to retrieve the post author, the post date and post time from the posts table in my database. However, I can't think of a valid structure to retrieve the number of comments (linked via a post_id) from the comments table in my database, and meanwhile keeping a clean MVC approach.
So my blog controller is structured like this:
Code:
function blog() {
$data['posts'] = $this->Posts_model->get_all_posts();
$this->load->view('blog_view', $data);
}
Model:
Code:
function get_all_posts() {
$q = $this->db->get('posts');
return $q->result();
}
And my view file looks like this:
Code:
<?php if (count($posts)): ?>
<?php foreach ($posts as $post): ?>
<div class="metadata"><?php echo $post['post_author']; ?> | <?php echo $post['post_date']; ?> at <?php echo $post['post_time']; ?> | NUMBER OF COMMENTS HERE</div>
<?php endforeach; ?>
<?php endif; ?>
Now I want to show <?php echo $...['number_of_comments']; ?> in the metadata <div> too, keeping a clean MVC structure. I know how to count comments in a model. All I gotta do is something like this:
Code:
function count_all_comments($post_id) {
$this->db->where('post_id', $post_id);
$q = $this->db->count_results('comments');
return $q->result();
}
But where do I get the $post_id from while running an foreach loop in the view? I know I can directly call this model action from the view file, but that is not respecting the MVC principles. Also.. how do I incorporate this into my controller?
All help is welcome, if you guys suggest a totally different structure I am also willing to learn from that. And the next step is doing a structure like:
if 0 -> 0 comments
if 1 -> 1 comment
if >1 -> x comments
Thank you for reading!