假设我有一个模型 Foo
,并且我正在更改属性 getter。代码如下:
class Foo extends Model
{
protected $table = 'foo';
public function getSomeBarAttribute($value)
{
return some_function($value);
}
}
有没有一种方法可以在变异之前访问属性的原始值?
/**
* The model attribute's original state.
*
* @var array
*/
protected $original = array();
getOriginal()
方法只返回数据库属性到 Array 类型。因此,getAttributes
和 setAttributes
等值不包括在内。
Array 返回 [key => value],这足以创建新的 Eloquent 实例。如果您想使用计算旧属性的 GetAttributes
,则可以在使用原始值的 getAttributes
之前创建新的模型实例。
$currentSomeBar = $foo->some_bar
$oldFoo = new Foo($foo->getOriginal());
$oldSomeBar = $oldFoo->some_bar;
rawSomeBar
的新函数,它返回$this->attributes['some_bar']
。 - Ahmed Nuaman