简体   繁体   中英

How correctly display item with comments using 2 tables

I have made something like facebook wall. I used 2 tables for storing info: #_ post and # _post_comments. #_ post contains wall post and # _post_comments contains post's comments.

I want to know how can I display all the info, using 2 separate models(for each query) or using join. Right now I used really bad, in my opinion solution:

I created model for #__post table, and used query something like this:

SELECT * FROM #__post

And then in template I made this:

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...
} 
}

What I would do differently is run one SQL query and then fill in the arrays in the loop. Example (not tested):

$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));
  }
}

Then you would have to do some tricks with sorting maybe, but hope you get the idea. So in the end you should have one $post array like this:

$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(...)
  ),
  /* ... */
);

It might be not pretty in terms of PHP, but you could save tons of executing time with one SQL query instead of N queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM