2015-09-06 42 views
0

我添加了幾個模型和一個控制器。Laravel5.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

在dev上安裝https://github.com/barryvdh/laravel-debugbar讓你知道爲什麼它很慢。 – ceejayoz

回答

1

我假設您要執行您在示例中指定的所有代碼,包括註釋行。我認爲你正在搜索的是渴望加載

它可以很容易地用來避免N + 1查詢問題並提高性能。

你應該使用類似:

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

此外,您還可以指定嵌套關係。

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

更多詳情here!文檔示例非常容易理解!

此外,使用分析器來分析您的應用程序請求會很有用。那裏有很多,barryvdh/laravel-debugbar就是其中之一。

+0

我有一個線程超過30,000個職位。我編輯了線程表並添加了thread_replay,並在category.blade.php中爲此更改:** $ a = $ thread-> thread_reply + 1 ** – Pionas

+0

顯然,您可以使用[Eager Loading constraining](http://laravel.com) /docs/5.1/eloquent-relationships#constraining-eager-loads)來完成工作,只選擇一組特定的線程。它是完全一樣的語法:) –

+0

如果您想「存儲」(然後獲取)一些關於您的線程的元數據信息,您可以編輯ForumThread模型並添加一個名爲「posts_count」的訪問器來計算帖子總數: )。看看[這裏](http://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators)。 –