在laravel 5.3中使用带有访问器的演员表 [英] Using casts with accessor in laravel 5.3
问题描述
我想使用laravel(5.3)雄辩的$casts
属性,例如protected $casts = ["example" => "object"]
和getExampleAttribute
访问器,但是看来访问器会丢弃$casts
行为.这对我来说至关重要,因为我想将JSON对象存储在数据库中并为其设置默认值,例如:
I want to use laravel (5.3) eloquent's $casts
attribute like protected $casts = ["example" => "object"]
with getExampleAttribute
accessor, but as it seems accessor discards the $casts
behaviour. It's crucial for me since I want to store JSON object in database and have a default value for it, e.g:
public function getExampleAttribute($value) {
if($value === NULL)
return new \stdclass();
return $value
}
所以我永远不会在我的视图中得到NULL值.除了在访问器和mutator中显式实现强制转换逻辑之外,还有什么方法比之更容易?
so I would never get NULL values in my views. Is there a way to do it easier than just implementing casts logic within accessor and mutator explicitly?
推荐答案
如果您希望该字段显式遵循$casts
定义,则可以使用以下解决方案.您只需要从访问器mutator内部手动调用cast函数:
If you want the field to explicitly follow the $casts
definition, the following solution works. You just need to manually call the cast function from inside an accessor mutator:
public function getExampleAttribute($value)
{
// force the cast defined by $this->casts because
// this accessor will cause it to be ignored
$example = $this->castAttribute('example', $value);
/** set defaults for $example **/
return $example;
}
这种方法假设您将来可能会更改演员表,但是如果您知道它始终是一个array/json字段,则可以这样替换castAttribute()
调用:
This method sort of assumes that you might change the cast in the future, but if you know it's always going to be an array/json field then you can substitute the castAttribute()
call like this:
public function getExampleAttribute($value)
{
// translate object from Json storage
$example = $this->fromJson($value, true)
/** set defaults for $example **/
return $example;
}
这篇关于在laravel 5.3中使用带有访问器的演员表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!