我添加了几个模型和一个 Controller 。
Controller
论坛:
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就是其中之一。
关于mysql - Laravel 5.1 Eloquent 慢动作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32427575/