Laravel 预加载优化评论问题

Laravel Eager Loading Optimization Comments Issue

所以我只是搞乱了预加载的东西,我一直在检查我拉了多少 Sql 语句,我真的觉得我这里的东西确实有效,但我觉得我可以做这是一种更好的预加载方式。有没有人有任何建议或可能阻止来自 运行 查询的每条评论的方法?...

这是我的控制器函数 Show()

public function show($id)
{
    //
    $posts = Post::with(['user','comments'])->where('user_id', $id)->get();

    foreach($posts as $post) {
      echo "<hr /><h2>" . $post->title . "</h2>";
      echo "<p><u style='font-size: 0.8rem;'>By: ". $post->user->name ."</i></u> | <u style='font-size: 0.8rem;'>Date:" . $post->created_at->format('n-j-Y') . "</u>";
      echo "<br />" . $post->content . "</p><hr />";
      echo "<h3>Comments</h3>";
      if($post->comments->isNotEmpty()) {
        foreach($post->comments as $comment) {
          echo "<u>" . $comment->user->name . "</u><br />" . $comment->comment . "<br /><br />";
        }
      } else {
        echo "Sorry there are no comments yet.";
      }
    }
}

这是它拉取的数据,显示在我调用的页面上。请记住,我知道我应该使用视图,但我这样做主要是为了学习。

select * from posts where user_id = ?

select * from users where users.id in (?)

select comments.*, taggables.post_id as pivot_post_id, taggables.taggable_id as pivot_taggable_id, taggables.taggable_type as pivot_taggable_type from comments inner join taggables on comments.id = taggables.taggable_id where taggables.post_id in (?, ?, ?) and taggables.taggable_type = ?

Posts网页:


糟糕的标题

作者:Moriah Mayer | Date:7-30-2018

取消 iure recusandae consequatur 别名。 Et non ratione unded deleniti。 Est delectus recusandae consectetur quia tempore。 Asperiores ea et voluptas molestias.


评论

select * from users where users.id = ? limit 1

朱莉娅·曼特五世

这是一个随机的 Post 评论希望有用。

select * from users where users.id = ? limit 1

莫里亚·迈尔

这是另一个随机 Post 评论,希望有用。


新PHP标题

作者:Moriah Mayer | Date:7-30-2018

这是我们在没有教程的情况下创建的第一个内容。


评论

select * from users where users.id = ? limit 1

Timmothy Fay DDS

你这里的 post 很有趣。


Moriahs 惊人 Post

作者:Moriah Mayer | Date:7-30-2018

在这里,我们将向您展示我们可以为项目做些什么,您可以从中学到很多东西 post。


评论

抱歉,还没有评论。

您还需要预先加载与每个 comment 相关的 user。您可以使用点表示法急切加载嵌套关系:

$posts = Post::with(['user', 'comments.user'])->where('user_id', $id)->get();

现在每个评论都会让用户预先加载,不会运行新查询。