Home> PHP Framework> Laravel> body text

Laravel8 has new features! Targeting N+1 issues by disabling delay

藏色散人
Release: 2021-10-13 15:11:00
forward
1497 people have browsed it

在Laravel8 has new features! Targeting N+1 issues by disabling delay8 has new features! Targeting N+1 issues by disabling delay 8的下一个版本中,您可以完全禁用延迟加载,从而导致异常:

防止N+1问题? @themsaid最近对框架的贡献允许您完全禁用延迟加载(将引发异常)...

只能在非生产环境下禁用它,这样在一个进程中出错时生产不会崩溃!

下周发布! pic.twitter.com/5Q9YpCLRze

— Taylor Otwell (@taylorotwell) May 19, 2021

防止开发中的延迟加载可以帮助您在开发过程的早期捕获N+1错误。Laravel8 has new features! Targeting N+1 issues by disabling delay8 has new features! Targeting N+1 issues by disabling delay生态系统有各种工具来识别N+1查询。然而,这种方法通过抛出一个异常来将问题放在前面和中心。

推荐:《laravel教程

演示

让我们快速浏览一下这个特性,通过旋转框架8.x分支的开发版本,因为在撰写本文时这个特性还没有推出。一旦发布,您将拥有此功能,而无需切换到最新的8.x分支。

安装

首先,创建一个新的应用程序:

laravel new strict-lazy-demo
Copy after login

接下来,我们将更新composer.json中的laravel/framework版本,通过将版本调整为8.x-dev,确保我们拥有此功能(如果您在下一版本之前尝试此功能):

{ "require": { "laravel/framework": "8.x-dev" } }
Copy after login

接下来,运行composer update以确保获得此分支的最新版本代码:

composer update laravel/framework
Copy after login

此时,您应该设置首选数据库。我喜欢使用Laravel8 has new features! Targeting N+1 issues by disabling delay8 has new features! Targeting N+1 issues by disabling delay的默认值运行本地MySQL实例,即使用root用户而不使用密码。我发现在本地使用默认的.env值很方便,无需任何配置即可快速开始。

mysql -uroot -e"create database strict_lazy_demo"
Copy after login

配置所选数据库后,请确保可以迁移:

php artisan migrate:fresh
Copy after login

Demo Data

我们将创建一个Post模型,并从User模型中定义一对多关系,以演示此功能。我们将首先创建Post模型和附带的文件:

# 使用迁移和工厂创建模型 php artisan make:model -mf Post
Copy after login

首先,让我们定义Post迁移和工厂配置:

// 您的文件名将根据创建文件的时间而有所不同。 // 2021_05_21_000013_create_posts_table.php Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignIdFor(\App\Models\User::class); $table->string('title'); $table->longText('body'); $table->timestamps(); });
Copy after login

接下来,根据上述模式定义PostFactory定义方法:

/** * Define the model's default state. * * @return array */ public function definition() { return [ 'user_id' => \App\Models\User::factory(), 'title' => $this->faker->sentence(), 'body' => implode("\n\n", $this->faker->paragraphs(rand(2,5))), ]; }
Copy after login

最后,打开DatabaseSeeder文件,并在run()方法中添加以下内容:

/** * 数据库填充程序。 * * @return void */ public function run() { \App\Models\User::factory() ->has(\App\Models\Post::factory()->count(3)) ->create() ; }
Copy after login

关联模型并防止延迟加载

现在我们已经创建了迁移文件、填充文件和模型,我们已经准备好将User与Post模型关联起来以演示该特性。向User模型添加以下方法,以给用户一个与Posts的关联:

// app/Models/User.php /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function posts() { return $this->hasMany(Post::class); }
Copy after login

有了这些,我们就可以迁移和填充数据库了:

php artisan migrate:fresh --seed
Copy after login

如果一切顺利,我们将在控制台中看到如下内容:

Laravel8 has new features! Targeting N+1 issues by disabling delay8 has new features! Targeting N+1 issues by disabling delay

现在,我们可以使用tinker检查我们的填充数据和关系:

php artisan tinker >>> $user = User::first() => App\Models\User {#4091 id: 1, name: "Nedra Hayes", email: "bruen.marc@example.com", email_verified_at: "2021-05-21 00:35:59", created_at: "2021-05-21 00:35:59", updated_at: "2021-05-21 00:35:59", } >>> $user->posts => Illuminate\Database\Eloquent\Collection {#3686 all: [ App\Models\Post {#3369 id: 1, ...
Copy after login

$user->posts属性实际上调用了数据库,因此是“惰性”的,但没有进行优化。延迟加载的便利性很好,但从长远来看,它可能带来沉重的性能负担。

禁用延迟加载

现在我们已经设置了模型,我们可以在应用程序中禁用延迟加载。您可能只希望在非生产环境中禁用,这很容易实现!打开“AppServiceProvider”类并将以下内容添加到“boot()”方法:

// app/Providers/AppServiceProvider.php public function boot() { Model::preventLazyLoading(! app()->isProduction()); }
Copy after login

当你再次运行php artisan tinker, 此时您应该会收到延迟加载违规的异常:

php artisan tinker >>> $user = \App\Models\User::first() => App\Models\User {#3685 id: 1, name: "Nedra Hayes", email: "bruen.marc@example.com", email_verified_at: "2021-05-21 00:35:59", #password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi", #remember_token: "jHSxFGKOdw", created_at: "2021-05-21 00:35:59", updated_at: "2021-05-21 00:35:59", } >>> $user->posts Illuminate\Database\LazyLoadingViolationException with message 'Attempted to lazy load [posts] on model [App\Models\User] but lazy loading is disabled.'
Copy after login

如果要观察在视图中使用延迟加载时发生的情况,请按照如下方式修改默认路由:

Route::get('/', function () { return view('welcome', [ 'user' => \App\Models\User::first() ]); });
Copy after login

接下来,在welcome.blade.php文件中某处添加以下内容:

Posts

@foreach($user->posts as $post)

{{ $post->title }}

{{ $post->body }}

@endforeach
Copy after login

如果您通过 Valet 或artisan serve加载您的应用程序,您应该会看到类似于以下错误页面的内容:

Laravel8 has new features! Targeting N+1 issues by disabling delay8 has new features! Targeting N+1 issues by disabling delay

尽管您在开发过程中会遇到异常,但只要您在服务提供者中正确设置了环境检查,意外部署触发延迟加载的代码将继续工作。

学习更多

您可以了解此功能是如何实现的:8.x 添加 eloquent 严格加载模式 - 拉取请求 #37363。非常感谢 Mohamed Said、贡献者,当然还有 Taylor Otwell 添加了 the polish 有条件地禁用延迟加载。

Original address: https://laravel-news.com/disable-eloquent-lazy-loading-during-development

Translation address: https://learnku.com/laravel/t /61661

The above is the detailed content of Laravel8 has new features! Targeting N+1 issues by disabling delay. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!