Welcome Guest, Not a member yet? Register   Sign In
Showing number of comments in blog (while listing all posts)
#1

[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">&lt;?php echo $post['post_author']; ?&gt; | &lt;?php echo $post['post_date']; ?&gt; at &lt;?php echo $post['post_time']; ?&gt; | NUMBER OF COMMENTS HERE</div>
&lt;?php endforeach; ?&gt;
&lt;?php endif; ?&gt;

Now I want to show &lt;?php echo $...['number_of_comments']; ?&gt; 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!


Messages In This Thread
Showing number of comments in blog (while listing all posts) - by El Forum - 09-07-2009, 06:36 AM



Theme © iAndrew 2016 - Forum software by © MyBB