扫码关注官方订阅号
我最近开始使用 Model::preventLazyLoading() 但即使关系未加载但有时可能会加载,它实际上也会引发错误
Model::preventLazyLoading()
像资源 'discount' => $this->whenLoaded('meta', $this->meta->discount ?? 0),
'discount' => $this->whenLoaded('meta', $this->meta->discount ?? 0),
laravel版本:9.17.0
让 PHP 在此处解析您的语法。无论如何,它都必须加载 $this->meta,因为当 PHP 解析您的代码时,它优先于 whenLoaded() 方法.
PHP
$this->meta
whenLoaded()
$this->whenLoaded('meta', $this->meta->discount ?? 0)
这就是为什么 whenLoaded() 可以采用 closure() 来避免加载关系,除非它们实际上已加载。此方法将在满足 whenLoaded() 条件后首先评估闭包。
closure()
$this->whenLoaded('meta', function () { return $this->meta->discount ?? 0; });
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
让
PHP在此处解析您的语法。无论如何,它都必须加载$this->meta,因为当PHP解析您的代码时,它优先于whenLoaded()方法.$this->whenLoaded('meta', $this->meta->discount ?? 0)这就是为什么
whenLoaded()可以采用closure()来避免加载关系,除非它们实际上已加载。此方法将在满足whenLoaded()条件后首先评估闭包。$this->whenLoaded('meta', function () { return $this->meta->discount ?? 0; });