在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!

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.


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 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment