以下是以下伪代码的实际代码:
// 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 = '
- ';
foreach( $all_comments as $comment ) {
$comments .= '
'.$comment->user_comment.'
by: '.$comment->byy.'
';// print replies
$comments .= print_comments( $topic_id, $comment->comment_id ); // recursive
$comments .= '
';}
$comments .= '
';return $comments;
}
?>
将上面的代码放在视图文件的顶部.现在使用以下行显示/回显您的评论和回复.
<?php echo print_comments( Yii::$app->getRequest()->getQueryParam('id'), 0); ?>
(上一个答案)
您可以尝试遵循此伪代码:
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
foreach( $all_comments as $comment ) {
$comment->user_comment
by: $comment->byy
// print replies
print_comments( $topic_id, $comment->comment_id ); // recursive
}
}
优点:更易于理解和实施.
缺点:使用大量查询.
任何其他方式来克服利弊?
请记住,当与分页一起使用时,这种做法很难实现.
>使用单个查询获取所有评论和回复>将所有这些格式化为comment =>回复关系>循环关系并显示它