首页 > 解决方案 > 需要帮助优化 laravel 复杂查询

问题描述

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 循环的情况下做到这一点

调试栏结果: 来自调试栏的屏幕截图

标签: mysqllaravelperformanceoptimizationeloquent

解决方案


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

还有,posts需要INDEX(created_at)

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


推荐阅读