mysql - 需要帮助优化 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 循环的情况下做到这一点
调试栏结果: 来自调试栏的屏幕截图
解决方案
post_categories
看起来像一个多:多映射表。如果是这样,请遵循http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table中的索引建议
还有,posts
需要INDEX(created_at)
。
如需进一步讨论,请提供SHOW CREATE TABLE
和EXPLAIN SELECT ...
推荐阅读
- c# - 如何将 DataGridView 的颜色值传递给 ListBox?
- reactjs - 如何在反应原生平面列表中访问数组中的嵌套对象
- r - 以组内匹配的行元素为条件进行变异
- elasticsearch - 所有特定属性的 Elasticsearch 动态模板
- python - 对受 CloudFlare 保护的 API 的 Python 请求返回 403
- python - 我正在尝试交换列表中的两个元素,但是在第一次交换之后,它会不断被交换,因为它符合要交换的条件
- java - 如何使用@WebMvcTest 连接千分尺
- jquery - 使用带有ajax jquery的codeignter上传多个文件
- matplotlib - 如何在 Matplotlib 中获得固定高度(以像素为单位)、固定数据 x/y 纵横比并自动移除移除水平空白边距?
- jquery - 使用 jQuery 时获取 rails 对象 id 的问题