I have this in Model:
public function index_loop() {
$post_user = $this->db->query("SELECT posts.post_title, posts.post_content, posts.post_date, users.username FROM posts LEFT JOIN users ON posts.user_id = users.user_id ORDER BY posts.post_ID DESC");
//$categories = $this->db->query("SELECT categories.cat_name, categories.cat_id FROM
//$comments = $this->db->query("SELECT COUNT(comment_id) FROM comments WHERE
return $post_user->result_array();
}
What I need is to show categories for each post and comments (although I guess if I figure out categories passing than comments are the same way)
in View file:
<?php foreach($posts as $zz) { ?>
<div class="article">
<h2><?php echo $zz['post_title']; ?></h2>
<p>Posted by <a href=""><?php echo $zz['username']; ?></a> | Filed under <a href="#">templates</a>, <a href=>internet</a></p>
<p><?php echo $zz['post_content']; ?></p>
<p><a href=>Read more</a> | <a href=>Comments (5)</a> | <?php echo $zz['post_date']; ?></p>
</div> <?php } ?>
So, if I want to loop categories on each blog I need that blogs ID, how do I get it if I make all queries from Model?
The same for comments
Is it good that I make one big complicated DB query ( which is hard but I can do it) or I can do 2 or 3 separate smaller queries?
Codeigniter allows you to return database results as objects (model objects, for example), which makes data much easier to work with. You can issue your initial query to the
Poststable, include theposts.idfield in your result set, and pass the name of yourPost_modelclass to the$db->query->result()function to tell codeigniter that you’d like your result(s) returned as instances of thePost_modelclass.You can then define methods on the
Post_modelclass toGetCategoriesbypost_idandGetCommentsbypost_id, and then call these methods to populate your$categoriesand$commentscollections for eachPost_modelreturned from your query.Here’s an example, i hope it helps:
Then, in your view, you can access your $posts array as Post_model objects rather than as result_arrays:
As for the question of efficiency, it’s going to depend on a lot of factors (is the database located on the same machine as the web server? how many posts are there? etc). A single large query will typically perform quicker than several smaller ones, but it will require profiling to really determine whether the performance gains are worth seeking. I always prefer to try and write readable/understandable code rather than optimize at the expense of adding complexity.