mysql - Laravel 5.1 Eloquent 慢动作

标签 mysql laravel-5 eloquent laravel-5.1

我添加了几个模型和一个 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/

相关文章:

php - Laravel + MySQL - 存储 Eloquent 命名空间

php - 按 "x Days Old"列出结果

php - 如何将随机字符串列添加到 laravel 迁移

mysql - 如何通过laravel模型获取对象中对象的对象

php - Laravel - 如何添加另一个联接来获取多个表

php - laravel Eloquent 嵌套评论和回复

mysql - 将图像存储到数据库 blob;从数据库检索到 Picturebox

mysql - 通过 codeigniter 使用一个连接和一个查询访问多个数据库

php - laravel Controller 名称应该是复数还是单数?

php - 如何删除 Eloquent 中的多态关系?