Laravel模型同名访问器如何调用数据库sale字段默认值?
解决方案:复用数据库sale字段的Laravel访问器写法
当访问器与数据库字段同名时,直接调用$this->sale会触发访问器的递归调用,导致Undefined property错误。要获取数据库中存储的原始字段值,可通过以下两种方式实现:
方法1:直接访问模型的attributes数组
Laravel模型会将从数据库加载的原始字段值存储在$this->attributes关联数组中,直接访问该数组可绕过访问器调用:
public function getSaleAttribute() { $offer = $this->offer()->orderBy('created_at', 'DESC')->active()->first(); if($offer) { $sale = $this->price - ($this->price * $offer->percentage / 100); } else { $sale = $this->attributes['sale']; } return number_format($sale, 2); }
方法2:使用getOriginal()官方方法
框架提供的getOriginal()方法是更安全的选择,它专门用于获取字段的原始数据库值,当字段不存在时会返回null:
public function getSaleAttribute() { $offer = $this->offer()->orderBy('created_at', 'DESC')->active()->first(); if($offer) { $sale = $this->price - ($this->price * $offer->percentage / 100); } else { $sale = $this->getOriginal('sale'); } return number_format($sale, 2); }
注意事项
确保sale字段已正确配置在模型的$fillable属性中(或$guarded设为[]),否则模型可能无法正确加载该字段的原始值。
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

