【问题标题】:need help optimizing laravel complex query需要帮助优化 laravel 复杂查询
【发布时间】:2021-07-06 09:45:16
【问题描述】:

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 的帖子 second 用于获取帖子中的类别。

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

调试栏结果: screenshot from debugbar

【问题讨论】:

    标签: mysql laravel performance optimization eloquent


    【解决方案1】:

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

    另外,posts 需要 INDEX(created_at)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2012-10-14
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多