首页 > 解决方案 > 在 Laravel 8.x 中循环嵌套注释

问题描述

在 Laravel 8.x 中,我正在尝试创建一个允许您回复评论的博客评论系统。如果回复评论,则评论被分配一个parent_idid他们正在回复的评论的。目前,当我用回复循环评论时,它只会输出一个回复 1 深度循环,如下例所示:

当前问题的示例:

User1:随机帖子 1..
> User2:此文本是对 User1 对帖子 1 的
回复 User6:随机帖子 2..
User7:随机帖子 3..

我想要达到的目标:

User1:随机帖子 1..
> User2:此文本是对帖子 1 的 User1 的响应
>> User3:此文本是对帖子 1 的 User2 的响应
>>> User4:此文本是对帖子 1 的 User3 的响应
> >> User5:此文本是对帖子 1 的 User3 的回复
User6:随机帖子 2..
User7:随机帖子 3..

我当前的代码

模型:
class PostComment extends Model
{
    use HasFactory;

    public function replies()
    {
        return $this->hasMany($this, 'parent_id');
    }
}

刀:

@foreach ($comments as $comment)

    <p> {{ $comment->user->name }} : {{ $comment->comment }} </p>

    @foreach ($comment->replies as $reply)

        <p> {{ $reply->user->name }} : {{ $reply->comment }} </p>

    @endforeach

@endforeach

现在,如果我@foreach ($comment->replies as $reply)在评论循环中添加 4 次,它将显示回复.. 但当然这是不切实际的,因为评论可以有无限的回复。我希望你能理解我想要表达的意思,我非常不擅长解释事情。

非常感谢任何帮助:)

标签: phplaravellaravel-blade

解决方案


创建两个刀片文件

  1. comment-list.blade.php
  2. child-comment-list.blade.php

comment-list.blade.php 文件中

@if(count((array)$comments))
    @foreach ($comments as $comment)
    
        <p> {{ $comment->user->name }} : {{ $comment->comment }} </p>
    
       @include('child-comment-list',['comments'=>$comment->replies])
    
        @endforeach
@endif
    

child-comment-list.blade.php 文件中

@if(count((array)$comments))
 @foreach($comments as $comment)
 
  <p> {{ $comment->user->name }} : {{ $comment->comment }} </p>
   @if(count((array)$comment->replies))

            @include('child-comment-list',['comments'=>$comment->replies])

   @endif
 @endforeach

所以在你当前的文件中

@include('comment-list',['comments'=>$comments]);

推荐阅读