PHP MYSQL - 显示多线程注释不起作用

时间:2014-06-16 03:19:34

标签: php mysql multithreading nested threaded-comments

这就是我的数据库的样子

评论

id 1 - (primary key)
user_id 2
comment - I need help

id 2 - (primary key)
user_id 
comment - I'm going to sleep now

id 3 - (primary key)
user_id 2
comment - Watching the news. 

回复

id 1
comment_id 1 (foreign key)
reply - what do you need help with?

id 2
comment_id 1 (foreign key)
reply - i can help you!

id 3
comment_id 1 (foreign key)
reply - i don't understand!

id 4
comment_id 2 (foreign key)
reply - OK have a good night.

<小时/> 问题是,我希望评论显示如下所示:

评论 - 我需要帮助

---回复 - 您需要什么帮助?
----我可以帮到你! -----我不明白!

评论 - 我现在要睡觉了

---回复 - 好好过一个晚上。

评论 - 看新闻。

---没有回复

不喜欢这个,这就是我现在所得到的。

评论 - 我需要帮助

---回复 - 您需要什么帮助?

评论 - 我需要帮助

---我可以帮到你!

评论 - 我需要帮助

----我不明白!

评论 - 我现在要睡觉了

---回复 - 好好过一个晚上。

评论 - 看新闻。

---没有回复

这是我的查询

$query = $db->prepare("SELECT 

comments.id, 
comments.user_id,
comments.comment, 

replies.id,
replies.comment_id,
replies.reply

FROM comments
LEFT JOIN replies 
ON comments.id = replies.comment_id
WHERE comments.user_id = ? ORDER BY comments.id DESC");

try {
$query->execute();              

while($row = $query->fetch(PDO::FETCH_ASSOC)) {

$comm_id = $row['id'];
$comm_user_id = $row['user_id']; 
$comm = $row['comment'];

$re_id = $row['id']; 
$re_comm_id = $row['comment_id'];
$re_reply = $row['reply'];

echo $comm." - ".$re_reply;

}

} catch (PDOException $e) {
echo $e->getMessage();
exit();
}

问题显然在查询结构中,但我不确定如何构建它以便我可以获得所需的结果。

我希望我能够清楚地解释自己,感谢您提前提供任何帮助。

1 个答案:

答案 0 :(得分:0)

首先更改查询,以便replies.id有一个别名,以便稍后引用:

SELECT comments.id, comments.user_id, comments.comment, 
  replies.id reply_id, replies.comment_id, replies.reply
FROM comments
LEFT JOIN replies 
ON comments.id = replies.comment_id
WHERE comments.user_id = ? ORDER BY comments.id DESC

您可以先通过comment_id对回复进行分组。

<?php
$comments = array();
$comm_replies = array();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {

    $comm_id = $row['id'];
    $comm_user_id = $row['user_id']; 
    $comm = $row['comment'];

    if (empty($row['reply_id'])) {
      continue;    
    }

    $comments[$comm_id] = $comm;
    $comm_replies[$comm_id][] = $row;
}

foreach ($comments as $comm_id => $comm) {
    echo "comment - $comm\n";
    if (!isset($comm_replies[$comm_id])) {
        continue;
    }

    $prefix = '---';
    foreach ($comm_replies[$comm_id] as $reply_id => $row) {
        echo "$prefix $row['reply_id'], $row['reply']\n";
        $prefix .= '-';
    }
}