Eloquent模型'with'在控制器内部调用

时间:2015-12-02 16:37:11

标签: php laravel laravel-5 eloquent

假设我有一个Post hasMany模型Comment $post->comments模型。所以基本上我会做$post = App\Post::with('comments')->findOrFail($id); return view('someview', compact('post')); 的评论。

在某些网站上,我看到人们在控制器中执行此操作:

@foreach($post->comments as $comment)

然后在视图中:

$post->comments ...

据我了解,with('comments')始终会附上评论,无需致电$post = App\Post::findOrFail($id); return view('someview', compact('post')); 。这不正确吗?

如果是这样,那么上面和下面的区别是什么:

控制器

@foreach($post->comments as $comment)

查看

.container { width:1025px; display:block; height:400px; } .container:before{ content:''; width:1025px; height:15px; background-color:blue; display:block; position:absolute; top:20%; } .container div{ display:inline-block; float:left; background-size: 22px 22px; padding-left:22px; } .container div.span:before{ content:''; background:url('http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/firey-orange-jelly-icons-alphanumeric/070242-firey-orange-jelly-icon-alphanumeric-information3-sc49.png'); background-repeat:no-repeat; background-position:left; display:block; width:22px; height:22px; background-size: contain; } .container div.down:after{ content:''; background:url('http://cdn.mysitemyway.com/etc-mysitemyway/icons/legacy-previews/icons/firey-orange-jelly-icons-alphanumeric/070242-firey-orange-jelly-icon-alphanumeric-information3-sc49.png'); background-repeat:no-repeat; background-position:left; display:block; width:22px; height:22px; background-size: contain; } ....

1 个答案:

答案 0 :(得分:1)

它被称为Eager Loading:http://laravel.com/docs/5.1/eloquent-relationships#eager-loading

急切加载不会影响您的示例。这是一个更好的用例:

$posts = App\Post::orderBy('id')->take(10)->get();

foreach ($posts as $post)
{
    echo $post->comments;
}

Eloquent将为数据库创建11个查询,这是不好的。 1个查询获取帖子,10个查询获取每个帖子的评论。

当您急切加载您的关系时,Eloquent只会进行另一个查询。

$posts = App\Post::with('comments')->orderBy('id')->take(10)->get();

foreach ($posts as $post)
{
    echo $post->comments;
}

此示例将创建2个查询:1个用于获取所有帖子,另一个用于获取帖子'评价。

select * from posts

select * from comments where post_id in (1, 2, 3, 4, 5, ...)