Laravel更快地查询控制器或视图中的所有内容 [英] Laravel Faster to query everything in controller or view
问题描述
查询控制器中的所有内容并返回每个查询或在使用时在视图中查询是否更快?
Is it faster to query everything in the controller and return every query back, or query in view as you use it?
假设所有模型都有关系
示例:
在cotroller中进行所有操作,然后返回
Do everythig in cotroller and then return
Public function articlesHome($id)
{
$art = Articles::find($id);
$cit = Articles::city();
$tag = Articles::tags();
Return view('articles', compact('art', 'tag', 'cit');
}
或者在视图中(在控制器返回$ article之后)
Or in view (after controller returned $article)
{{ $article->name }}
...
{{ $article->city->name }}
...
@foreach($article->tags as tag)
{{ tag->name }}
@endforeach
实践中最好的,速度更快.
Which is best in practice and faster.
推荐答案
从性能上来说,这只是寻找一种方法来减少获得相同结果的数据库查询数.
Performance wise it's just a matter of finding a way to get fewer database queries to achieve the same result.
一种好的方法是让laravel在单个命令中为您完成此操作:
A good approach would be let laravel do it for you in a single command:
Public function articlesHome($id)
{
$article = Articles::whereId($id)->with('city','tags')->get();
Return view('articles', compact('article');
}
您的看法将是相同的.文章关系已经建立,因此不会进行任何额外的查询.
Your view would be the same. The articles relationships is already built, so no extra queries will be made.
{{ $article->name }}
...
{{ $article->city->name }}
...
@foreach($article->tags as tag)
{{ tag->name }}
@endforeach
这篇关于Laravel更快地查询控制器或视图中的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!