0

我正在尝试加载 Category(children's) 以在 html 表中查看它们并像这样对它们进行分页:

// 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 !如果确实如此...如何解决?

4

1 回答 1

0

您拨打的with电话没有进一步的效果。直接运行关系方法时不考虑。您可以使用急切加载的约束执行以下操作:

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'));
} 
于 2016-12-28T08:46:22.607 回答