Laravel 中 Blade 的嵌套评论
Nested comments with Blade in Laravel
我正在尝试在 Laravel 中使用 Blade 生成嵌套评论。好像我必须制作一个 blade 模板,为每个评论预配置无限嵌套评论,它是 child 评论。但我希望评论自动生成。
这是我的评论模型:
class Comment extends Model {
protected $table = 'comments';
public function user()
{
return $this->hasOne('App\Models\User', 'id', 'user_id');
}
public function post()
{
return $this->hasOne('App\Models\Post', 'id', 'post_id');
}
public function children()
{
return $this->hasMany('App\Models\Comment', 'parent_id', 'id');
}
}
在我看来我正在做
@foreach($comments as $comment)
<!-- Comment markup -->
@if($comment->children->count() > 0)
@foreach($comment->children as $child)
<!-- Child comment markup -->
@if($child->children->count() > 0) // I have to do this unlimited times
@foreach ....
@endforeach
@endif
@endif
@endforeach
我正在寻找一种方法来自动执行此操作,也许可以使用某个函数或其他东西。
您基本上是在寻找递归视图。这在下面的示例中有所说明(实际上不需要提取 show
视图,但这是个好主意)。
resources/views/comments/index.blade.php
@foreach($comments as $comment)
{{-- show the comment markup --}}
@include('comments.show', ['comment' => $comment])
@if($comment->children->count() > 0)
{{-- recursively include this view, passing in the new collection of comments to iterate --}}
@include('comments.index', ['comments' => $comment->children])
@endif
@endforeach
resources/views/comments/show.blade.php
<!-- Comment markup -->
我正在尝试在 Laravel 中使用 Blade 生成嵌套评论。好像我必须制作一个 blade 模板,为每个评论预配置无限嵌套评论,它是 child 评论。但我希望评论自动生成。
这是我的评论模型:
class Comment extends Model {
protected $table = 'comments';
public function user()
{
return $this->hasOne('App\Models\User', 'id', 'user_id');
}
public function post()
{
return $this->hasOne('App\Models\Post', 'id', 'post_id');
}
public function children()
{
return $this->hasMany('App\Models\Comment', 'parent_id', 'id');
}
}
在我看来我正在做
@foreach($comments as $comment)
<!-- Comment markup -->
@if($comment->children->count() > 0)
@foreach($comment->children as $child)
<!-- Child comment markup -->
@if($child->children->count() > 0) // I have to do this unlimited times
@foreach ....
@endforeach
@endif
@endif
@endforeach
我正在寻找一种方法来自动执行此操作,也许可以使用某个函数或其他东西。
您基本上是在寻找递归视图。这在下面的示例中有所说明(实际上不需要提取 show
视图,但这是个好主意)。
resources/views/comments/index.blade.php
@foreach($comments as $comment)
{{-- show the comment markup --}}
@include('comments.show', ['comment' => $comment])
@if($comment->children->count() > 0)
{{-- recursively include this view, passing in the new collection of comments to iterate --}}
@include('comments.index', ['comments' => $comment->children])
@endif
@endforeach
resources/views/comments/show.blade.php
<!-- Comment markup -->