首页 > 解决方案 > 如何使用嵌套的项目列表来减少数据库查询的数量标签?Laravel 5.8:当我使用嵌套的项目列表时,我得到了太多的查询。这是视图中的菜单。我已经完成了项目的嵌套菜单,但在我看来,它需要太多的查询(我的 30 个项目列表需要 10 个额外的查询),尽管我使用了“急切加载”。在模型中: public function children() { return $this->hasMany(Item::class, 'parent_id', 'id'); 它的存储库:(使用急切加载 [wit

问题描述

标签: phplaravellaravel-5

解决方案


您也必须急切地加载子子项:

$columns = ['id', 'parent_id', 'title'];

$result = $this->startConditions()
    ->select($columns)
    ->with(['children:id,title,parent_id', 'children.children:id,title'])
    ->get();
return $result;

考虑本文中的以下示例:https ://laravel-news.com/eloquent-eager-loading

$posts = App\Post::with('author.profile')->get();
$posts->map(function ($post) {
    return $post->author->profile;
});

在这里你可以看到他们使用点符号来获取深层关系with()


推荐阅读