Laravel5.1雄辩的慢动作

时间:2015-09-06 19:43:23

标签: mysql laravel-5 eloquent laravel-5.1

我添加了一些模型和一个控制器。

控制器

论坛:

public function showCategory($alias)
{
    $page_title = trans('forum.forum').' :: '.trans('static.website_title');

    $category_info = ForumCategory::where('category_alias', $alias)->first();

    return view('layout.pages.forum.category', compact('category_info'));
}

模型

ForumCategory

public function threads()
{
    return $this->hasMany('App\Forum\ForumThread', 'category_id');
}

ForumThread

public function posts()
{
    return $this->hasMany('App\Forum\ForumPost', 'thread_id');
}

category.blade.php:

@extends('layout.default')

@section('content')

{{ $category_info->category_alias }}

{{--*/ $ThreadList = $category_info->threads()->paginate(20) /*--}}

    @foreach( $ThreadList as $thread )
    {{--*/ $a = $thread->posts->count() /*--}}
        <a href="{{URL::to('/forum', array($category_info->category_alias, $thread->thread_alias))}}">{{ $thread->thread_id }} - {{ $thread->thread_subject }} - {{ $a }}</a><br /><br />
    @endforeach
@stop

页面渲染时间为:~0.701548814774秒。 在我看来,我觉得很慢...... 我怎么能加速这个?

1 个答案:

答案 0 :(得分:1)

我假设您要执行示例中指定的所有代码,包括注释行。我认为您正在搜索的是急切加载

它可以很容易地用于避免N + 1查询问题并提高性能。

你应该使用类似的东西:

ForumCategory::with('threads')->where('category_alias', $alias)->first();

此外,您可以指定嵌套关系。

ForumCategory::with('threads.posts')->where('category_alias', $alias)->first();

更多详情here!文档示例非常容易理解!

此外,使用分析器分析您的应用程序请求会很有用。那里有很多,barryvdh/laravel-debugbar就是其中之一。