跳过模型访问器 [英] Skip model accessor

查看:58
本文介绍了跳过模型访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了一个名为Run的模型,其中包含以下方法:

I got a model called Run which contains this method:

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

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

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

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?

推荐答案

这是正确的方法

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

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

小心!

正如Maksym Cierzniak在评论中解释的那样,getOriginal()不仅跳过突变器,而且还从数据库中读取对象时返回该字段的原始"值.因此,如果您已经修改了模型的属性,则不会返回修改后的值,它仍将返回原始值.从模型类中获取未变异值的更一致,更可靠的方法是从attributes属性中检索它,如下所示:

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 attributes property like this:

$this->attributes['name']

但是请注意,attributes是受保护的属性,因此您不能从模型类外部进行此操作.在这种情况下,您可以使用

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

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

或者马克西姆的技巧来自下面的评论.

or Maksym's technique from his comment below.

这篇关于跳过模型访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆