我试图显示评论和回复,但我真的不知道如何做。这是我的桌子。
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>';
}
}
?> 发布于 2016-09-19 17:59:17
下面是以下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>
}Pros:更易于理解和实现。
Cons:使用了很多查询。
还有其他克服缺点的方法吗?
请记住,当与分页一起使用时,这种方法的实现更加困难。
发布于 2016-09-19 17:56:40
我对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();https://stackoverflow.com/questions/39577767
复制相似问题