【发布时间】:2021-09-17 12:55:15
【问题描述】:
我正在为我的博客 cmets 和回复使用急切加载。如果博客评论parent_id 为空,我对N+1 没有任何问题。但是,当我将评论分配给 parent_id 以创建回复嵌套时,就会导致 N+1 问题。
我试过调查这个问题,它似乎来自posts.comments.blade 和posts.comments-child.blade,但我不知道为什么。任何帮助表示赞赏。
评论后模型
public function user()
{
return $this->belongsTo(User::class);
}
public function replies()
{
return $this->hasMany($this, 'parent_id');
}
后控制器
$postComments = PostComment::where([
'post_id' => $post->id,
'parent_id' => null
])->with('user', 'replies')->get();
main.blade
@include('posts.comments', ['comments' => $postComments])
posts.cmets.blade & posts.cmets-child.blade
@foreach ($comments as $comment)
<h6>{{ $comment->user->name }}</h6>
<p>{{ $comment->comment }}</p>
<ul>
@include('posts.comments-child', ['comments' => $comment->replies])
</ul>
<hr>
@endforeach
【问题讨论】:
标签: php laravel laravel-blade