public function index() { $topics = Topic::paginate(30); return view('topics.index', compact('topics')); }
一对一关联模型 所有的 ORM 关联数据读取中都存在此问题,新手很容易踩到坑。进而导 致系统变慢,然后拖垮整个系统。
N+1 一般发生在关联数据的遍历时。在 resources/views/topics/_topic_list.blade.php 模板中,我们对 $topics 进行遍历,为了方便解说,我们将此文件里的代码精简为如下:
@if (count($topics)) <ul class="media-list"> @foreach ($topics as $topic) . . . {{ $topic->user->name }} . . . {{ $topic->category->name }} . . . @endforeach </ul> @else <div class="empty-block">暂无数据 ~_~ </div> @endif
为了读取 user 和 category ,每次的循环都要查一下 users 和 categories 表,在本例子中我们查询了 30 条话题数据,那么最终我需要执行的查询语句就是 30 * 2 + 1 = 61 条语句。如果我第一次查询出来的是 N 条记录,那么最 终需要执行的 SQL 语句就是 N+1 次
如何解决 N + 1 问题?
我们可以通过 Eloquent 提供的预加载 来解决此问题: app/Http/Controllers/TopicsController.php
app/Http/Controllers/TopicsController.php
<?php . . . class TopicsController extends Controller { . . . public function index() { $topics = Topic::with('user', 'category')->paginate(30); return view('topics.index', compact('topics')); } . . . }
方法 with() 提前加载了我们后面需要用到的关联属性 user 和 category ,并做了缓存。后面即使是在遍历数据 时使用到这两个关联属性,数据已经被预加载并缓存,因此不会再产生多余的 SQL 查询: