关于 Model appends
class User extends Model
{
protected $appends = ['is_adult'];
public function getIsAdultAttribute()
{
return $this->attribute['age'] ?? 0 > 18;
}
}
getXxxAttribute 是一个很用的特性,但如果 model 中自动 append 就会产生很多问题,如你在 select 的时候,没有 age 字段,依然会帮你加上 append 的字段,这有时会带来很多问题。建议不使用 $append 这个属性。在需要的时候,在 controller 层加载这个属性。其实访问器这个东西在使用的时候也需要谨慎,主要在对原属性进行修改的时候不方便获取原值,当属性的多层关联时也会行程套娃。
// model
class User extends Model
{
public function getIsAdultAttribute()
{
return $this->attribute['age'] ?? 0 > 18;
}
}
// controller
$user = User::first();
$user->append('is_adult');