我有以下代码,但即使我在本地开发环境中也不会抛出异常
$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 关系。
为什么不起作用?
您必须将
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());
}