我剛開始我的第一個CI應用程序。我有一個顯示一些帖子的視圖。每篇文章可以有多個評論,我希望顯示每篇文章旁邊的評論總數。CodeIgniter:幫助這個查詢
到目前爲止,我所有的數據庫調用都在我的控制器(將改變這一點)。
function index(){
$data['query'] = $this->db->get('posts');
$this->load->view('blog_view', $data);
}
筆者認爲:
<?php foreach($query->result() as $row):
<div class="post-box">
<p><?php echo $row->body; ?><small> added by <?php echo $row->username; ?> on <?php echo date ('d/m/Y',strtotime($row->created)); ?> <a href="<?php echo base_url(); ?>blog/comments/<?php echo $row->id; ?>"><img src="<?php echo base_url(); ?>images/comments_icon.png" /> 0</a></small></p>
</div>
<?php endforeach; ?>
我想要得到的意見,其中comment.post_id =當前記錄的ID總數。並將其顯示在評論圖標旁邊。
與此最爲欣賞的任何幫助,
比利
UPDATE
控制器:
function index(){
//load the model
$this->load->model('City_model');
//call the model method
$data->posts = $this->City_model->get_posts();
$this->load->view('blog_view', $data);
}
模型(city_model.php):
<?php
class City_model extends Model{
function get_posts($id = NULL) {
//define optional id for single post
//if an id was supplied
if ($id != NULL) {
$this->db->where('id',$id);
}
// execute query
$query = $this->db->get('posts');
//make sure results exist
if($query->num_rows() > 0) {
$posts = $query->result();
} else {
return FALSE;
}
//create array for appended (with comments) posts
$appended_posts_array = array();
//loop through each post
foreach ($posts as $post) {
//get comments associated with the post
$this->db->where('post_id', $post->id)
$comments = $this->db->get('comments');
//if there are comments, add the comments to the post object
if($comments->num_rows() > 0) {
$post->comments = $comments;
}
else {
$post->comments = array();
}
//rebuild the returned posts with their comments
$appended_posts_array[] = $post;
}
//if post id supplied, only return the single post object
if ($id != NULL) {
return $appended_registration_array[0];
}
else {
return $appended_registration_array;
}
}
}
@jondavidjohn:我刪除了原來的答案,因爲你的答案更全面,更多的是MVC的「精神」,所以說。我同意OP應該通過「快速修復」選擇這種類型的解決方案。「+1抽出時間來說明正確的做法 – 2011-01-08 21:11:40