我做了一些类似facebook墙的东西。我使用了两个表来存储信息:#_post和#_post_comments#_post包含wallpost,#_post_comments包含post的注释。
我想知道如何使用2个单独的模型(每个查询)或使用联接来显示所有信息。现在我使用了非常糟糕的,在我看来的解决方案:
我为#__post表创建了模型,并使用了类似这样的查询:
SELECT * FROM #__post
然后在模板中我做了这个:
foreach ($posts as $post) {
echo $post->title;
echo $post->text;
echo 'Comments start here';
$comments = "SELECT * #__post_comments WHERE id = $post->id";
foreach ($comments as $comments) {
echo $comments->comment;
etc...
}
}
不同的做法是运行一个SQL查询,然后填充循环中的数组。示例(未测试):
$comments = "select * from post_comments
join posts on post_comments.post_id = posts.id
order by post_comments.id desc, posts.id desc";
foreach ($comments as $comment) {
if (!$posts[$comment['post_id']]) {
$posts[$comment['post_id'] = array("post_data" => XXX, "comments" => array(YYY));
}
}
然后你可能需要做一些排序技巧,但希望你能明白。所以最后你应该有一个$post数组,如下所示:
$posts = array(
[0] => array(
"post_data" => array("title" => "XXX", "create_time" => "YYY"),
"comments" => array(...)
),
[1] => array(
"post_data" => array("title" => "XXX", "create_time" => "YYY"),
"comments" => array(...)
),
/* ... */
);
就PHP而言,它可能并不漂亮,但使用一个SQL查询而不是N个查询可以节省大量的执行时间。