dongliufa6380 2018-01-17 21:20
浏览 41
已采纳

Laravel 5.4 Mutator无法正常工作

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

1

1,2

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:

["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).

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • du656637962 2019-07-29 09:45
    关注

    First, Mutator functions are like "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.

    Hope it helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据