我添加了几个模型和一个控制器。
控制者
论坛:
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'));
}
楷模
论坛类别
public function threads()
{
return $this->hasMany('App\Forum\ForumThread', 'category_id');
}
论坛主题
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秒。
我认为这很慢...
我该如何加快速度?
最佳答案
我假设您要执行示例中指定的所有代码,包括注释行。我认为您要搜索的是“渴望加载”。
它可以轻松用于避免N + 1查询问题并提高性能。
您应该使用类似:
ForumCategory::with('threads')->where('category_alias', $alias)->first();
另外,您可以指定嵌套关系。
ForumCategory::with('threads.posts')->where('category_alias', $alias)->first();
更多详细信息here!该文档示例非常容易理解!
同样,使用探查器探查您的应用程序请求也很有用。那里有很多,barryvdh/laravel-debugbar是其中之一。