需要帮助优化 Laravel 复杂查询

时间:2021-07-06 09:45:16

标签: mysql laravel performance optimization eloquent

Laravel 代码:

        $posts = array();
        $allPosts = DB::table('post_categories')
                ->Join('posts', 'posts.id', '=', 'post_categories.posts_id')
                ->select('posts.title','posts.id','posts.body','posts.created_at')
                ->where('post_categories.categories_id','!=',5)
                ->orderBy('posts.created_at','desc')
                ->get();
                
        foreach ($allPosts as $post){
            $categories = DB::table('post_categories')
                ->Join('categories', 'categories.id', '=', 'post_categories.categories_id')
                ->select('categories.name','categories.id')
                ->where('post_categories.posts_id','=',$post->id)
                ->get();
            $post->categories = $categories;
            array_push($posts,$post);
        }

模型关系: 帖子 1 - m post_categories m - 1 类别

第一个查询用于获取没有类别号 5 的帖子 第二个用于获取帖子中的类别。

问题是由于 for 循环,我有一个 n+1 查询。 所以我想知道在没有 for 循环的情况下是否有更好的方法来做到这一点

调试栏结果: screenshot from debugbar

1 个答案:

答案 0 :(得分:0)

post_categories 看起来像一个多:多映射表。如果是这样,请遵循 http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

中的索引建议

此外,posts 需要 INDEX(created_at)

如需进一步讨论,请提供SHOW CREATE TABLEEXPLAIN SELECT ...