我知道可以为单个字段定义访问器和修改器,例如:
public function setSomeAttribute($value) {
// set the attribute
}
public function getSomeAttribute() {
// return the attribute}
}
但是,有没有可能定义一个回调方法来处理所有属性的获取和设置?
原因在于,我想即时将任何空值转换为 null 值,以保持数据库的清洁,并允许可空字段为空而不是空字符串(如果有更好的方法,请告诉我!)
我正在寻找像这样的东西:
public function setAttribute($property,$value) {
$this->$property = empty($value) ? null : $value;
}
更新:
感谢Chris Goosey,我找到了适合我的解决方案。我扩展了Eloquent模型方法setAttribute,并在值为空时将其设置为列默认值。这通常是我的数据库中的null、零或空字符串,所以对我有效!
public function setAttribute($key, $value)
{
// Convert empty values to their default values (e.g. null, zero)
if(empty($value) && $this->getSchema()->hasColumn($key)) {
$value = $this->getSchema()->getColumn($key)->getDefault();
}
parent::setAttribute($key,$value);
}