我试图显示评论和回复,但我真的不知道如何做到这一点。这是我的桌子。
comment_id | byy | user_comment | topic_id | parent_id |
1 |obi |comment 1 | 1 | 0 |
2 |chima |comment 2 | 1 | 0 |
3 |eze |comment 1 reply | 1 | 1 |
4 |david |comment 2 reply | 1 | 2 |
我写的这段代码只是为了只显示注释,但我希望注释显示评论的回复(如果有的话)。在显示下一条注释
之前<?php
$querycomment = comment::find()->where(['topic_id'=> Yii::$app->getRequest()->getQueryParam('id')])->all();
foreach ($querycomment as $detail) {
if($detail['parent_id']==0) {
echo 'Country Name: '.$detail['user_comment'].'</br>';
echo 'State Name: '.$detail['byy'].'</br>';
echo 'City Name: '.$detail['name'].'</br>';
echo '</br>';
}
}
?>
我不熟悉Yii。但是您可以使用递归实现这一点。尝试实现类似于下面的内容:
function show_replies($parent_id = 0, $level = 0) {
$query = "select * from comments where parent_id = $parent_id";
$result = mysql_query($query);
if (!$result || !mysql_num_rows($result)) {
return;
}
while($detail = mysql_fetch_array($result)) {
$space ='';
for ($i = 0; $i < $level; $i++) {
$space .= "--";
}
echo $space.'Country Name: '.$detail['user_comment'].'</br>';
echo $space.'State Name: '.$detail['byy'].'</br>';
echo $space.'City Name: '.$detail['name'].'</br>';
show_replies($detail['comment_id'], $level + 1);
}
}
show_replies();
以下是pseudocode
的实际代码:
<?php
// print comments and/or replies body
function print_comments( $topic_id, $parent_id ) {
$all_comments = Comment::find()
->where(
'topic_id' => $topic_id,
'parent_id' => $parent_id
)->all();
if( empty($all_comment) ) {
return "";
}
$comments = '<ul>';
foreach( $all_comments as $comment ) {
$comments .= '<li>
<p> '.$comment->user_comment.' </p>
<p> by: '.$comment->byy.' </p>';
// print replies
$comments .= print_comments( $topic_id, $comment->comment_id ); // recursive
$comments .= '</li>';
}
$comments .= '</ul>';
return $comments;
}
?>
将上面的代码放在视图文件的顶部。现在使用下面的行来显示/回显你的评论和回复。
<?php echo print_comments( Yii::$app->getRequest()->getQueryParam('id'), 0); ?>
(先前的回答)
您可以尝试遵循以下pseudocode
:
print_comments( queryParam(id), 0); // parent_id = 0
// print comments and/or replies body
print_comments ( $topic_id, $parent_id ) {
$all_comments = Comment::find()
->where(
topic_id => $topic_id,
parent_id => $parent_id
)->all();
if( $all_comment count = zero )
return
<ul>
foreach( $all_comments as $comment ) {
<li>
<p> $comment->user_comment </p>
<p> by: $comment->byy </p>
// print replies
print_comments( $topic_id, $comment->comment_id ); // recursive
</li>
}
</ul>
}
优点:更容易理解和实现。缺点:使用大量查询。
还有其他方法可以克服缺点吗??
请记住,当与分页一起使用时,这种方法更难实现。
- 使用单一查询获取所有评论和回复
- 格式化所有评论=>回复关系
- 遍历关系并显示它