【问题标题】:N+1 eager loading in Laravel 8.x BladeLaravel 8.x Blade 中的 N+1 预加载
【发布时间】:2021-09-17 12:55:15
【问题描述】:

我正在为我的博客 cmets 和回复使用急切加载。如果博客评论parent_id 为空,我对N+1 没有任何问题。但是,当我将评论分配给 parent_id 以创建回复嵌套时,就会导致 N+1 问题。

我试过调查这个问题,它似乎来自posts.comments.bladeposts.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();

ma​​in.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


    【解决方案1】:

    您的 N+1 问题来自&lt;h6&gt;{{ $comment-&gt;user-&gt;name }}&lt;/h6&gt; 的回复

    最好也加载那些

    $postComments = PostComment::where([
        'post_id' => $post->id,
        'parent_id' => null
    ])->with('user', 'replies.user')->get();
    

    如果回复有更多回复等等,您仍然会遇到问题。

    【讨论】:

      猜你喜欢
      • 2016-12-15
      • 2022-01-26
      • 2015-06-11
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      相关资源
      最近更新 更多