laravel 跳过模型存取器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17543843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:06:48  来源:igfitidea点击:

Skip model accessor

phplaravel

提问by LHolleman

I got a model called Run which contains this method:

我有一个名为 Run 的模型,其中包含此方法:

public function getNameAttribute($name){
    if($name == 'Eendaags')
        return $this->race_edition->race->name;

    return $this->race_edition->race->name.' '.$name;
}

I need this setup for laravel administrator, since alot of runs will have the same name and the only difference is the race name. But in 1 place in the website i need to get the name only, without mutating. Is this possbile?

我需要为 laravel 管理员设置此设置,因为很多运行将具有相同的名称,唯一的区别是比赛名称。但是在网站的 1 个地方,我只需要获取名称,而无需更改。这是可能的吗?

回答by alioygur

this is the correct way

这是正确的方法

// that skips mutators
$model->getOriginal('name');

https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_getOriginal

https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_getOriginal

Edit:Careful!

编辑:小心!

As Maksym Cierzniak explained in the comments, getOriginal()doesn't just skip mutators, it also returns the "original" value of the field at the time the object was read from the database. So if you have since modified the model's property, this won't return your modified value, it will still return the original value. The more consistent and reliable way to get the un-mutated value from within the model class is to retrieve it from the attributesproperty like this:

正如 Maksym Cierzniak 在评论中所解释的那样,getOriginal()它不仅会跳过修改器,还会返回从数据库读取对象时字段的“原始”值。所以如果你已经修改了模型的属性,这不会返回你修改后的值,它仍然会返回原始值。从模型类中获取未突变值的更一致和可靠的方法是从attributes属性中检索它,如下所示:

$this->attributes['name']

But be aware that attributesis a protected property, so you can't do that from outside the model class. In that case, you can use

但请注意,这attributes是一个受保护的属性,因此您不能在模型类之外执行此操作。在这种情况下,您可以使用

$model->getAttributes()['name']`

or Maksym's technique from his comment below.

或 Maksym 的技术来自他下面的评论。

回答by atm

I was running into an issue with Eloquent accessors and form model binding - by formatting an integer with money_format, the value was no longer being loaded into the form number input field.

我遇到了 Eloquent 访问器和表单模型绑定的问题 - 通过使用 money_format 格式化整数,该值不再加载到表单编号输入字段中。

The workaround I am using is to create an accessor with a different name:

我使用的解决方法是创建一个具有不同名称的访问器:

public function getRevenueDollarsAttribute($value)
{
    return money_format('$%i', $this->revenue);
}

This provides me with an accessor without affecting the form model binding.

这为我提供了一个访问器,而不会影响表单模型绑定。