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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.
