简体   繁体   English

Laravel 5.4 Mutator不起作用

[英]Laravel 5.4 Mutator not working

I have a mutator which is not working, I've looked through here, tried some suggestions and yet nothing appears to get it working. 我有一个无法正常工作的转换器,我在这里浏览了一下,尝试了一些建议,但似乎没有任何东西可以使它正常工作。

Here is my Model: 这是我的模特:

...

protected $fillable = [
    'energy_types'
];

...

public function getEnergyTypesAttribute($value)
{
    $types = explode(',', $value);
    $fuels = array();
    foreach($types as $type){
        switch ($type){
            case '2':
                $fuelType = 'Gas (Reticulated)';
                break;
            case '3':
                $fuelType = 'Gas (Bottled)';
                break;
            default:
                $fuelType = 'Electricity';
        }
        $fuels[] = array(   "id" => $type,
                            "name" => $fuelType);
    }

    return $fuels;
}

Stored in the database as so: 如此存储在数据库中:

energy_types energy_types

1 1

1,2 1,2

1 1

Controller: 控制器:

if($participant->isRetailer){
       $retail = Retailer::find($participant->id);
       $participant->energyTypes = $retail->energy_types;

If I do a dump here of $retail , energy_types is still just like so: 如果我在这里转储$ retailenergy_types仍然像这样:

["energy_types"]=>
    string(3) "1,2"

I've tried changing how I get $retail , re-migrated, tried even setting an attribute (doesn't work also). 我尝试更改$ retail的方式 ,重新迁移,甚至尝试设置属性(也不起作用)。

What am I doing wrong? 我究竟做错了什么?

First, Mutator functions are like "setEnergyTypesAttribute". 首先,Mutator函数类似于“ setEnergyTypesAttribute”。

Your code snippets, however, is showing that you're trying to define an Accessor. 但是,您的代码段显示您正在尝试定义访问器。

Anyway, if you are trying to add a custom attribute to a Model when retrieving data from database, here is how you do it. 无论如何,如果您试图在从数据库中检索数据时向模型添加自定义属性,请按以下步骤进行。

...
protected $appends = ['foo'];
...
public function getFooAttribute()
{
    return $this->attributes['bar'] . ' foo'; 
}

where "bar" is an original attribute in the Model. 其中“ bar”是模型中的原始属性。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM