app\Providers\AppServiceProvider.php 中的 preventLazyLoading() 不起作用

问题描述 投票:0回答:1

我有以下代码,但即使我在本地开发环境中也不会抛出异常

$user = User::findOrFail(34);
$user->videos;

app\Providers\AppServiceProvider.php

...
use Illuminate\Database\Eloquent\Model;
...

public function boot()
{
  Model::preventLazyLoading(true);
}

https://laravel.com/docs/9.x/eloquent-relationships#preventing-lazy-loading

防止懒加载后,Eloquent 会抛出一个 当您的 Illuminate\Database\LazyLoadingViolationException 异常 应用程序尝试延迟加载任何 Eloquent 关系。

为什么不起作用?

laravel eloquent orm lazy-loading eager-loading
1个回答
0
投票

您必须将

User
模型更改为
Model

use Illuminate\Database\Eloquent\Model;
 
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Model::preventLazyLoading(! $this->app->isProduction());
}

为了避免在生产现场出现混乱的错误消息

!$this->app->isProduction()
.

为了防止

preventLazyLoading
preventSilentlyDiscardingAttributes
preventAccessingMissingAttributes
只包含一行代码
Model::shouldBeStrict(! $this->app->isProduction())

use Illuminate\Database\Eloquent\Model;
 
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Model::shouldBeStrict(! $this->app->isProduction());
}
© www.soinside.com 2019 - 2024. All rights reserved.