我有一个变形器不起作用,我看了看这里,尝试了一些建议,但似乎没有任何东西使它起作用。
这是我的模型:
...
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;
}存储在数据库中的内容如下:
energy_types
1
1,2
1
主计长:
if($participant->isRetailer){
$retail = Retailer::find($participant->id);
$participant->energyTypes = $retail->energy_types;如果我在这里转储$retail,energy_types仍然是这样的:
["energy_types"]=>
string(3) "1,2"我尝试过改变获得$retail的方式,重新迁移,甚至设置属性(也不起作用)。
我做错了什么?
发布于 2019-07-29 09:45:55
首先,Mutator函数类似于"setEnergyTypesAttribute“。
但是,您的代码片段显示您正在尝试定义访问器。
无论如何,如果您在从数据库检索数据时试图向Model添加自定义属性,下面是您如何做到的。
...
protected $appends = ['foo'];
...
public function getFooAttribute()
{
return $this->attributes['bar'] . ' foo';
}其中"bar“是模型中的原始属性。
希望能帮上忙。
https://stackoverflow.com/questions/48310168
复制相似问题