CodeIgniter: Displaying data from two tables in one loop
Let's say I have these two database tables:
blog comments
------- ----------
blog_id comment_id
title blog_id
content comment
Now I'd like to run through the 3 latest blog entries and display the title, content and the number of comments made on that entry.
For that, I created a Blog_model:
function get_entries($n)
{
if ($n < 1) {$n = 1;}
$this->db->order_by("blog_id", "desc");
$q = $this->db->get('blog', $n);
if($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
The model is loaded in the controller and passed on to the view:
$this->load->model('Blog_model');
$data['blog_rows'] = $this->Blog_model->get_entries(3);
$this->load->view('blog_view');
That gives me the three latest blog entries. I can now loop through the rows and display the content in the view like this:
<?php foreach ($blog_rows as $row): ?>
<h2><?=$row->title;?></h2>
<a href="#" class="comments">12></a>
<开发者_如何学JAVA;p><?=$row->content;?></p>
<?php endforeach; ?>
So far so good. But now the tricky part:
I'd like to display the number of comments associated with the displayed blog entry. How would I accomplish that, adhering to the CodeIgniter practices?
Here are two proposals for the model method: the first does a query for each blod row, while the second does an unique query wich is faster. the second query is not tested.
Model 1
function get_entries($n)
{
if ($n < 1) {$n = 1;}
$this->db->order_by("blog_id", "desc");
$q = $this->db->get('blog', $n);
if($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
foreach($data AS &$blog_e)
{
$q = "SELECT COUNT(*) AS count FROM comments WHERE blog_id = ?";
$query = $this->db->query($q,array($blog_e->blog_id);
$ncomments = $query->result_array();
$blog_e->n_comments = $ncomments[0]['count'];
}
}
Model 2
function get_entries($n)
{
if ($n < 1) {$n = 1;}
$q = "SELECT blog.blog_id,title,content,COUNT(comment_id) AS n_comments
FROM blog JOIN comments ON blog.blog_id = comments.blog_id
GROUP BY blog.blog_id,title,content
ORDER BY blog.blog_id DESC
LIMIT 0,?"
$query = $this->db->query($q,array($n));
if($query->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
View
<?php foreach ($blog_rows as $row): ?>
<h2><?=$row->title;?></h2>
<a href="#" class="comments"><?=$row->n_comments?>></a>
<p><?=$row->content;?></p>
<?php endforeach; ?>
精彩评论