Codeigniter 允许您将数据库结果作为对象(例如模型对象)返回,这使得数据更易于使用。您可以向Posts
表发出初始查询,在结果集中包含该posts.id
字段,并将Post_model
类的名称传递给$db->query->result()
函数以告诉 codeigniter 您希望将结果作为Post_model
类的实例返回。
然后,您可以在Post_model
类上定义GetCategories
bypost_id
和GetComments
bypost_id
方法,然后调用这些方法来填充您的$categories
和$comments
集合,以获取Post_model
从查询返回的每个。
这是一个例子,我希望它有帮助:
public class Post_model extends CI_Model
{
// All the properties in the Posts table, as well as a couple variables to hold the categories and comments for this Post:
public $id;
public $post_title;
public $post_content;
public $post_date;
public $username;
public $categories;
public $comments;
public function index_loop()
{
return $this->GetAllPosts();
}
// function to get all posts from the database, including comments and categories.
// returns an array of Post_model objects
public function GetAllPosts()
{
// define an empty array to hold the results of you query.
$all_posts = array();
// define your sql query. NOTE the POSTS.ID field has been added to the field list
$sql = "SELECT posts.id,
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";
// issue the query
$query = $this->db->query($sql);
// loop through the query results, passing a string to result() which represents a class to instantiate
//for each result object (note: this class must be loaded)
foreach($query->result("Post_model") as $post)
{
$post->categories = $this->GetPostCategories($post->id);
$post->comments = $this->GetPostComments($post->id);
$all_posts[] = $post;
}
return $all_posts;
}
// function to return categories for a given post_id.
// returns an array of Category_model objects.
public function GetPostCategories($post_id)
{
$sql = "SELECT category.id, ... WHERE post_id = ?";
$query = $this->db->query($sql, array($post_id));
$categories = array();
foreach($query->result("Category_model") as $category)
{
$categories[] = $category;
}
return $categories;
}
// function to return comments for a given post_id.
//returns an array of Comment_model objects
public function GetPostComments($post_id)
{
$sql = "SELECT comment.id, ... WHERE post_id = ?";
$query = $this->db->query($sql, array($post_id));
$comments = array();
foreach($query->result("Comment_model") as $comment)
{
$comments[] = $comment;
}
return $comments;
}
}
然后,在您看来,您可以将 $posts 数组作为 Post_model 对象而不是 result_arrays 访问:
<?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
<?php foreach($zz->categories as $category) {
echo '<a href="#">{$category->name}</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 } ?>
至于效率问题,这将取决于很多因素(数据库是否与 Web 服务器位于同一台机器上?有多少帖子?等等)。单个大型查询通常比几个较小的查询执行得更快,但需要进行分析才能真正确定性能提升是否值得寻求。我总是更喜欢尝试编写可读/可理解的代码,而不是以增加复杂性为代价进行优化。