php - 在 Laravel 8.x 中循环嵌套注释
问题描述
在 Laravel 8.x 中,我正在尝试创建一个允许您回复评论的博客评论系统。如果回复评论,则评论被分配一个parent_id
是id
他们正在回复的评论的。目前,当我用回复循环评论时,它只会输出一个回复 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 次,它将显示回复.. 但当然这是不切实际的,因为评论可以有无限的回复。我希望你能理解我想要表达的意思,我非常不擅长解释事情。
非常感谢任何帮助:)
解决方案
创建两个刀片文件
comment-list.blade.php
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]);
推荐阅读
- apex - 异步函数中的 RefreshApex
- vuejs2 - 如何在 vue js 中使用 bootstrap swiper
- c# - Azure App Config HMAC 身份验证返回未经授权的错误
- javascript - 如何预览客户端图像上传并通过 POST 请求(python/flask)提交
- aws-codebuild - 如何安装 netfx-4.7.2-devpack 因巧克力而失败
- firebase - 尝试在空对象引用上调用虚拟方法“java.lang.String com.practice.projectbm.Model.User.getName()”
- database - MongoDB $lookup 字段和 $ addedField 作为 foreignField
- google-cloud-platform - Google Cloud Logging:没有使用项目作为资源名称的 LogEntry
- asp.net - 如何从 ReactJS 将数据发布到 ASP.NET Core
- reactjs - 如何键入组件的链接类?