Laravel Faster to query everything in controller or view

后端 未结 3 1294
[愿得一人]
[愿得一人] 2021-01-27 01:13

Is it faster to query everything in the controller and return every query back, or query in view as you use it?

Assuming all the models had the relationship

Exam

3条回答
  •  孤城傲影
    2021-01-27 01:39

    Performance wise it's just a matter of finding a way to get fewer database queries to achieve the same result.

    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 
    

提交回复
热议问题