拉拉维尔渴望加载优化评论问题



所以我只是弄乱了急切加载的东西,我一直在检查我拉了多少 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.";
}
}
}

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

posts中选择 *,其中user_id= ?

users位置中选择usersid(?

选择"comments.*"、"taggables"。post_idpivot_post_idtaggables.taggable_idpivot_taggable_idtaggables.taggable_type作为commentspivot_taggable_type内联接taggablescomments.id=taggables.taggable_id哪里taggables.post_id(?, ?, ?) 和taggables.taggable_type= ?

帖子网页:


坏屁股标题

作者:莫里亚·梅耶 |日期:7-30-2018

Deserunt iure recusandae consequatur alias.Et non ratione unde deleniti.Est delectus recusandae consectetur quia tempore.Asperiores ea et voluptas molestias.


评论

users位置中选择usersid= ?限制 1

朱莉娅·曼特五世

这是一个随机的帖子评论,希望它有效。

users位置中选择 *usersid= ?限制 1

莫利亚·梅耶

这是另一个随机的帖子评论,希望它有效。


新的 PHP 标题

作者:莫里亚·梅耶 |日期:7-30-2018

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


评论

users位置中选择usersid= ?限制 1

蒂莫西·费伊 DDS

这是你在这里看到的一篇有趣的帖子。


莫里亚斯惊人的帖子

作者:莫里亚·梅耶 |日期:7-30-2018

在这里,我们将向您展示我们可以用我们对项目的思维方式做些什么,您可以从这篇文章中学到很多东西。


评论

抱歉,还没有评论。

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

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

现在,每个注释都将加载其用户渴望,并且不会运行新查询。

最新更新