Laravel8 has new features! Targeting N+1 issues by disabling delay
在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
接下来,我们将更新composer.json
中的laravel/framework
版本,通过将版本调整为8.x-dev
,确保我们拥有此功能(如果您在下一版本之前尝试此功能):
{ "require": { "laravel/framework": "8.x-dev" } }
接下来,运行composer update
以确保获得此分支的最新版本代码:
composer update laravel/framework
此时,您应该设置首选数据库。我喜欢使用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"
配置所选数据库后,请确保可以迁移:
php artisan migrate:fresh
Demo Data
我们将创建一个Post
模型,并从User
模型中定义一对多
关系,以演示此功能。我们将首先创建Post
模型和附带的文件:
# 使用迁移和工厂创建模型 php artisan make:model -mf Post
首先,让我们定义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(); });
接下来,根据上述模式定义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))), ]; }
最后,打开DatabaseSeeder
文件,并在run()
方法中添加以下内容:
/** * 数据库填充程序。 * * @return void */ public function run() { \App\Models\User::factory() ->has(\App\Models\Post::factory()->count(3)) ->create() ; }
关联模型并防止延迟加载
现在我们已经创建了迁移文件、填充文件和模型,我们已经准备好将User与Post模型关联起来以演示该特性。向User
模型添加以下方法,以给用户一个与Posts的关联:
// app/Models/User.php /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function posts() { return $this->hasMany(Post::class); }
有了这些,我们就可以迁移和填充数据库了:
php artisan migrate:fresh --seed
如果一切顺利,我们将在控制台中看到如下内容:
现在,我们可以使用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, ...
$user->posts
属性实际上调用了数据库,因此是“惰性”的,但没有进行优化。延迟加载的便利性很好,但从长远来看,它可能带来沉重的性能负担。
禁用延迟加载
现在我们已经设置了模型,我们可以在应用程序中禁用延迟加载。您可能只希望在非生产环境中禁用,这很容易实现!打开“AppServiceProvider”类并将以下内容添加到“boot()”方法:
// app/Providers/AppServiceProvider.php public function boot() { Model::preventLazyLoading(! app()->isProduction()); }
当你再次运行 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.'
如果要观察在视图中使用延迟加载时发生的情况,请按照如下方式修改默认路由:
Route::get('/', function () { return view('welcome', [ 'user' => \App\Models\User::first() ]); });
接下来,在 welcome.blade.php
文件中某处添加以下内容:
<h2 id="Posts">Posts</h2> @foreach($user->posts as $post) <h3 id="post-gt-title">{{ $post->title }}</h3> <p> {{ $post->body }} </p> @endforeach
如果您通过 Valet 或 artisan serve
加载您的应用程序,您应该会看到类似于以下错误页面的内容:
尽管您在开发过程中会遇到异常,但只要您在服务提供者中正确设置了环境检查,意外部署触发延迟加载的代码将继续工作。
学习更多
您可以了解此功能是如何实现的: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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

PHP unit testing tool analysis: PHPUnit: suitable for large projects, provides comprehensive functionality and is easy to install, but may be verbose and slow. PHPUnitWrapper: suitable for small projects, easy to use, optimized for Lumen/Laravel, but has limited functionality, does not provide code coverage analysis, and has limited community support.

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.
