简体   繁体   English

控制器内部雄辩的模型“ with”调用

[英]Eloquent model 'with' call inside the controller

Let's say I have a Post model that hasMany Comment model. 比方说,我有一个Post模型hasMany Comment模型。 So basically to get the comments I would do $post->comments . 所以基本上要获得评论,我会做$post->comments

On some websites, I have seen people do this in the controller: 在某些网站上,我看到人们在控制器中执行此操作:

$post = App\Post::with('comments')->findOrFail($id);

return view('someview', compact('post'));

and then inside the view: 然后在视图中:

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

To my understanding, $post->comments would always have the comments attached and there's no need to call with('comments') . 据我了解, $post->comments始终会附加注释,而无需调用with('comments') Is this not correct? 这不正确吗?

If so, then what is the difference between the above and the below: 如果是这样,那么上面和下面之间有什么区别:

Controller 控制者

$post = App\Post::findOrFail($id);

return view('someview', compact('post'));

View 视图

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

It's called Eager Loading: http://laravel.com/docs/5.1/eloquent-relationships#eager-loading 这称为“渴望加载”: http : //laravel.com/docs/5.1/eloquent-relationships#eager-loading

Eager loading will have no affect on your example. 渴望加载不会对您的示例产生影响。 Here is a better use case: 这是一个更好的用例:

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

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

Eloquent will create 11 queries to the database which is not good. Eloquent将对数据库创建11个查询,这不好。 1 query to get the posts, and 10 queries to get the comments for each post. 1个查询以获取帖子,10个查询以获取每个帖子的评论。

When you eager load your relation(s), Eloquent will only make one other query. 当您渴望加载您的关系时,Eloquent只会进行另一个查询。

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

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

This example will create 2 queries: 1 to get all posts and another to get the posts' comments. 本示例将创建2个查询:一个查询所有帖子,另一个查询评论。

select * from posts

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM