什么是 N+1 问题,以及如何解决 Laravel 的 N+1 问题?

file

对象关系映射(ORM)使得处理数据惊人地简单。由于以面向对象的方式定义数据之间关系使得查询关联模型数据变得容易,开发者不太需要关注数据底层调用。

ORM 的标准数据优化是渴望式加载相关数据。我们将建立一些示例关系,然后逐步了解查询随着渴望式加载和非渴望式加载变化。我喜欢直接使用代码来试验一些东西,并通过一些示例来说明渴望式加载是如何工作的,这将进一步帮助你理解如何优化查询。

介绍

在基本级别,ORM 是 “懒惰” 加载相关的模型数据。但是,ORM 应该如何知道你的意图?在查询模型后,您可能永远不会真正使用相关模型的数据。不优化查询被称为 “N + 1” 问题。当您使用对象来表示查询时,您可能在不知情的情况下进行查询。

想象一下,您收到了100个来自数据库的对象,并且每条记录都有1个关联的模型(即belongsTo)。使用ORM默认会产生101条查询; 对原始100条记录 进行一次查询,如果访问了模型对象上的相关数据,则对每条记录进行附加查询。在伪代码中,假设您要列出所有已发布帖子的发布作者。从一组帖子(每个帖子有一位作者),您可以得到一个作者姓名列表,如下所示:

$posts = Post::published()->get(); // 一次查询

$authors = array_map(function($post) {
    // 生成对作者模型的查询
    return $post->author->name;
}, $posts);

我们并没有告诉模型我们需要所有作者,因此每次从各个Post 模型实例中获取作者姓名时都会发生单独的查询 。

预加载

正如我所提到的,ORM 是 "懒惰" 加载关联。如果您打算使用关联的模型数据,则可以使用预加载将 101 次查询缩减为 2 次查询。您只需要告诉模型你渴望它加载什么。

以下是使用预加载的 Rails Active Record guide 中的示例.。正如您所看到的,这个概念与 Laravel's eager loading 概念非常相似。

# Rails
posts = Post.includes(:author).limit(100)

# Laravel
$posts = Post::with('author')->limit(100)->get();

通过从更广阔的视角探索,我发现我获得了更好的理解。Active Record 文档涵盖了一些可以进一步帮助该想法产生共鸣的示例。

Laravel 的 Eloquent ORM

Laravel 的 ORM,叫作 Eloquent, 可以很轻松的预加载模型,甚至预加载嵌套关联模型。让我们以Post模型为例,学习如何在 Laravel 项目中使用预先加载。
我们将使用这个项目构建,然后更深入地浏览一些预加载示例以进行总结。

构建

让我们构建一些 数据库迁移, 模型, 和  数据库种子 来体验预加载。如果你想跟着操作,我假设你有权访问数据库并且可以完成了基本的 Laravel 安装

使用 Laravel 安装器, 新建项目:

laravel new blog-example

根据你的数据库和选择编辑 .env 文件。

接下来,我们将创建三个模型,以便您可以尝试预加载嵌套关系。这个例子很简单,所以我们可以专注于预加载,而且我省略了你可能会使用的东西,如索引和外键约束。

php artisan make:model -m Post
php artisan make:model -m Author
php artisan make:model -m Profile

-m 标志创建一个迁移,以与将用于创建表模式的模型一起使用。

数据模型将具有以下关联:

Post -> belongsTo -> Author
Author -> hasMany -> Post
Author -> hasOne -> Profile

迁移

让我们为每个数据表创建一个简表结构。我只添加了 up() 方法,因为 Laravel 将会为新的数据表自动添加 down() 方法。这些迁移文件放在了 database/migrations/ 目录中:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * 执行迁移
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('author_id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * 回滚迁移
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAuthorsTable extends Migration
{
    /**
     * 执行迁移
     *
     * @return void
     */
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('bio');
            $table->timestamps();
        });
    }

    /**
     * 回滚迁移
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('authors');
    }
}
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProfilesTable extends Migration
{
    /**
     * 执行迁移
     *
     * @return void
     */
    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('author_id');
            $table->date('birthday');
            $table->string('city');
            $table->string('state');
            $table->string('website');
            $table->timestamps();
        });
    }

    /**
     * 回滚迁移
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('profiles');
    }
}

模型

你需要定义模型关联并通过预先加载来进行更多的实验。当你运行 php artisan make:model 命令的时候,它将为你创建模型文件。

第一个模型为 app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function author()
    {
        return $this->belongsTo(Author::class);
    }
}

接下来, app\Author.php 模型有两个关联关系:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }

    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

通过模型和迁移,你可以运行迁移并继续尝试使用一些种子模型数据进行预加载。

php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
Migrating: 2017_08_04_042509_create_posts_table
Migrated:  2017_08_04_042509_create_posts_table
Migrating: 2017_08_04_042516_create_authors_table
Migrated:  2017_08_04_042516_create_authors_table
Migrating: 2017_08_04_044554_create_profiles_table
Migrated:  2017_08_04_044554_create_profiles_table

如果你查看下数据库,你就会看到所有已经创建好的数据表!

工厂模型

为了让我们可以运行查询语句,我们需要创建一些假数据来提供查询,让我们添加一些工厂模型,使用这些模型来为数据库提供测试数据。

打开 database/factories/ModelFactory.php 文件并且将如下三个工厂模型添加到现有的 User 工厂模型文件中:

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->sentence,
        'author_id' => function () {
            return factory(App\Author::class)->create()->id;
        },
        'body' => $faker->paragraphs(rand(3,10), true),
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Author::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'bio' => $faker->paragraph,
    ];
});

$factory->define(App\Profile::class, function (Faker\Generator $faker) {
    return [
        'birthday' => $faker->dateTimeBetween('-100 years', '-18 years'),
        'author_id' => function () {
            return factory(App\Author::class)->create()->id;
        },
        'city' => $faker->city,
        'state' => $faker->state,
        'website' => $faker->domainName,
    ];
});

这些工厂模型可以很容易的填充一些我们可以用来查询的数据;我们也可以使用它们来创建并生成关联模型所需的数据。

打开 database/seeds/DatabaseSeeder.php 文件将以下内容添加到 DatabaseSeeder::run() 方法中:

public function run()
{
    $authors = factory(App\Author::class, 5)->create();
    $authors->each(function ($author) {
        $author
            ->profile()
            ->save(factory(App\Profile::class)->make());
        $author
            ->posts()
            ->saveMany(
                factory(App\Post::class, rand(20,30))->make()
            );
    });
}

你创建了五个 author 并遍历循环每一个 author ,创建和保存了每个 author 相关联的 profileposts (每个 authorposts 的数量在 20 和 30 个之间)。

我们已经完成了迁移、模型、工厂模型和数据库填充的创建工作,将它们组合起来可以以重复的方式重新运行迁移和数据库填充:

php artisan migrate:refresh
php artisan db:seed

你现在应该有一些已经填充的数据,可以在下一章节使用它们。注意在 Laravel 5.5 版本中包含一个 migrate:fresh 命令,它会删除表,而不是回滚迁移并重新应用它们。

尝试使用预加载

现在我们的前期工作终于已经完成了。 我个人认为最好的可视化方式就是将查询结果记录到 storage/logs/laravel.log 文件当中查看。

要把查询结果记录到日志中,有两种方式。第一种,可以开启 MySQL 的日志文件,第二种,则是使用 Eloquent 的数据库调用来实现。通过 Eloquent 来实现记录查询语句的话,可以将下面的代码添加到 app/Providers/AppServiceProvider.php boot() 方法当中:

namespace App\Providers;

use DB;
use Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function($query) {
            Log::info(
                $query->sql,
                $query->bindings,
                $query->time
            );
        });
    }

    // ...
}

我喜欢把这个监听器封装在配置检查的时候,以便可以控制记录查询日志的开关。你也可以从 Laravel Debugbar 获取到更多相关的信息。

首先,尝试一下在不使用预加载模型的时候,会发生什么情况。清除你的 storage/log/laravel.log 文件当中的内容然后运行 "tinker" 命令:

php artisan tinker

>>> $posts = App\Post::all();
>>> $posts->map(function ($post) {
...     return $post->author;
... });
>>> ...

这个时候检查你的 laravel.log 文件,你会发现一堆查询作者的查询语句:

[2017-08-04 06:21:58] local.INFO: select * from `posts`
[2017-08-04 06:22:06] local.INFO: select * from `authors` where `authors`.`id` = ? limit 1 [1]
[2017-08-04 06:22:06] local.INFO: select * from `authors` where `authors`.`id` = ? limit 1 [1]
[2017-08-04 06:22:06] local.INFO: select * from `authors` where `authors`.`id` = ? limit 1 [1]
....

然后,再次清空 laravel.log 文件,, 这次使用 with() 方法来用预加载查询作者信息:

php artisan tinker

>>> $posts = App\Post::with('author')->get();
>>> $posts->map(function ($post) {
...     return $post->author;
... });
...

这次你应该看到了,只有两条查询语句。一条是对所有帖子进行查询,以及对帖子所关联的作者进行查询:

[2017-08-04 07:18:02] local.INFO: select * from `posts`
[2017-08-04 07:18:02] local.INFO: select * from `authors` where `authors`.`id` in (?, ?, ?, ?, ?) [1,2,3,4,5]

如果你有多个关联的模型,你可以使用一个数组进行预加载的实现:

$posts = App\Post::with(['author', 'comments'])->get();

在 Eloquent 中嵌套预加载

嵌套预加载来做相同的工作。在我们的例子中,每个作者的 model 都有一个关联的个人简介。因此,我们将针对每个个人简介来进行查询。

清空 laravel.log 文件,来做一次尝试:

php artisan tinker

>>> $posts = App\Post::with('author')->get();
>>> $posts->map(function ($post) {
...     return $post->author->profile;
... });
...

你现在可以看到七个查询语句,前两个是预加载的结果。然后,我们每次获取一个新的个人简介时,就需要来查询所有作者的个人简介。

通过预加载,我们可以避免嵌套在模型关联中的额外的查询。最后一次清空 laravel.log 文件并运行一下命令:

>>> $posts = App\Post::with('author.profile')->get();
>>> $posts->map(function ($post) {
...     return $post->author->profile;
... });

现在,总共有三个查询语句:

[2017-08-04 07:27:27] local.INFO: select * from `posts`
[2017-08-04 07:27:27] local.INFO: select * from `authors` where `authors`.`id` in (?, ?, ?, ?, ?) [1,2,3,4,5]
[2017-08-04 07:27:27] local.INFO: select * from `profiles` where `profiles`.`author_id` in (?, ?, ?, ?, ?) [1,2,3,4,5]

懒人预加载

你可能只需要收集关联模型的一些基础的条件。在这种情况下,可以懒惰地调用关联数据的一些其他查询:

php artisan tinker

>>> $posts = App\Post::all();
...
>>> $posts->load('author.profile');
>>> $posts->first()->author->profile;
...

你应该只能看到三条查询,并且是在调用 $posts->load() 方法后。

总结

希望你能了解到更多关于预加载模型的相关知识,并且了解它是如何在更加深入底层的工作方式。 预加载文档 是非常全面的,我希望额外的一些代码实现可以帮助您更好的优化关联查询。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://laravel-news.com/eloquent-eager-...

译文地址:https://learnku.com/laravel/t/15077/what...

本帖已被设为精华帖!
本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 9
TigerLin

数据工厂填充的时候 出现了报错Type error: Argument 1 passed to Illuminate\Database\Eloquent\Factory::{closure}() must be an instance of Faker\Generator\Generator, instance of Faker\Generator given

5年前 评论

平时就这么用,没有深究,原来背后做了这么多优化,感慨选一款好框架对开发有多重要,这样想写烂代码都难。重新理解了选择比努力重要 :smile:

5年前 评论

@airsa 我用的5.5 也是抱这个错误。直接使用Faker $faker即可

5年前 评论

laravel 如果滥用的话,数据库表示压力很大。

5年前 评论

wherein 跟太多也不好

5年前 评论

工厂模型应该修改一下,不然seed之后会有一百多个Author:

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->sentence,
        'author_id' => function () {
            return factory(App\Author::class)->create()->id;
        },
        'body' => $faker->paragraphs(rand(3,10), true),
    ];
});

中去掉

  'author_id' => function () {
            return factory(App\Author::class)->create()->id;
        },

Profile的工厂模型也同样处理。
因为

 $author
            ->profile()
            ->save(factory(App\Profile::class)->make());

会自动添加author_id的值的,而工厂模型中的 factory(App\Author::class)->create()->id; 会创建新的一个author模型,这里无需再生成author_id
我试着运行了,需要以上修改才能正确生成数据(5 authors,5 profiles,100+ posts)。

5年前 评论

如果要在关联模型中限制数据的数量,比如一篇文章加前面两条评论,这样该怎么实现不至于产生N+1问题?

3年前 评论

原来底层是where in啊 但是where in 用多了也影响性能吧

3年前 评论
任飘渺

看完就忘了N+1问题原理,这篇文章至少看了五六次了, 这是怎么回事

3年前 评论
Summer (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!