我得到了一个名为Run的模型,它包含以下方法:
public function getNameAttribute($name){
if($name == 'Eendaags')
return $this->race_edition->race->name;
return $this->race_edition->race->name.' '.$name;
}
我需要为laravel管理员设置,因为很多跑步都有相同的名称,唯一的区别是比赛名称。但在网站的一个地方,我只需要得到名字,没有变异。这是负鼠吗?
这是的正确方式
// that skips mutators
$model->getOriginal('name');
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_getOriginal
编辑:小心
正如Maksym Cierzniak在评论中解释的那样,getOriginal()
不仅跳过了赋值函数,它还返回了从数据库中读取对象时字段的"原始"值。因此,如果您已经修改了模型的属性,这不会返回您修改后的值,它仍然会返回原始值。从模型类中获取未变异值的更一致和可靠的方法是从attributes
属性中检索它,如下所示:
$this->attributes['name']
但请注意,attributes
是受保护的属性,因此不能在模型类之外执行此操作。在这种情况下,您可以使用
$model->getAttributes()['name']`
或者马克西姆在下面的评论中的技巧。
自从Laravel 7.x和8.x以来,有一种新的方法可以访问完整的属性:
// that skips accessors
$model->getRawOriginal('name');
https://laracasts.com/discuss/channels/testing/how-to-disable-casting-during-testing
我遇到了Eloquent访问器和表单模型绑定的问题-通过使用money_format格式化整数,该值不再加载到表单编号输入字段中。
我使用的解决方法是创建一个具有不同名称的访问者:
public function getRevenueDollarsAttribute($value)
{
return money_format('$%i', $this->revenue);
}
这为我提供了一个访问器,而不会影响表单模型绑定。
对于Laravel 7.15.0
public function getOriginalNameAttribute()
{
return $this->attributes['name'];
}
// access it via
$user->originalName;