2016-12-28 48 views
0

我試圖加載類別(兒童)進行查看HTML表格和分頁他們是這樣的:是當前的例子使N + 1在我的代碼?

// show category children's 

public function show(subCategory $sections) 
    { 
     // Eager Loading the relationship 
     $sections->with('chlidrens'); 

     // paginate the category - childrens 

     $result = $sections->chlidrens()->orderBy('created_at','desc')->paginate(5); 

     return view('CompanySections.show',compact('sections','result')); 
    } 

我已經登錄第一頁這樣的SQL查詢:

[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `catnodestreetable` where `id` = ? limit 1"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `customers` where `customers`.`id` = ? limit 1"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select count(*) as aggregate from `catnodestreetable` where `catnodestreetable`.`node_parent_id` = ? and `catnodestreetable`.`node_parent_id` is not null"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `catnodestreetable` where `catnodestreetable`.`node_parent_id` = ? and `catnodestreetable`.`node_parent_id` is not null order by `created_at` desc limit 5 offset 0"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `categories` where `categories`.`id` = ? limit 1"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `clothes` where `clothes`.`item_id` = ? and `clothes`.`item_id` is not null limit 1"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `clothes` where `clothes`.`item_id` = ? and `clothes`.`item_id` is not null limit 1"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `clothes` where `clothes`.`item_id` = ? and `clothes`.`item_id` is not null limit 1"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `clothes` where `clothes`.`item_id` = ? and `clothes`.`item_id` is not null limit 1"} 
[2016-12-28 08:19:20] local.INFO: query {"query":"select * from `clothes` where `clothes`.`item_id` = ? and `clothes`.`item_id` is not null limit 1"} 

我的問題:是此代碼的原因N + 1 !! 如果它...如何解決它?

回答

0

with叫你做了沒有進一步的影響。當您直接運行關係方法時不考慮它。你可以做的是以下,使用eager loaded constraints

public function show(subCategory $sections) 
{ 
    $result = $sections->with(['children' => function($query) { 
     $query->orderBy('created_at', 'desc'); 
    }])->paginate(5); 

    return view('CompanySections.show',compact('sections','result')); 
} 
相關問題