我想使用 laravel (5.3) eloquent 的 $casts
属性,比如 protected $casts = ["example"=> "object"]
和 getExampleAttribute
访问器,但访问器似乎丢弃了 $casts
行为。这对我来说至关重要,因为我想将 JSON 对象存储在数据库中并为其设置默认值,例如:
public function getExampleAttribute($value) {
if($value === NULL)
return new \stdclass();
return $value
}
所以我永远不会在我的 View 中得到 NULL 值。有没有比在访问器和修改器中显式实现转换逻辑更容易的方法?
最佳答案
如果您希望该字段明确遵循 $casts
定义,则以下解决方案有效。您只需要从访问器修改器内部手动调用 cast 函数:
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;
}
这种方法假设您将来可能会更改类型转换,但如果您知道它始终是一个数组/json 字段,那么您可以像这样替换 castAttribute()
调用:
public function getExampleAttribute($value)
{
// translate object from Json storage
$example = $this->fromJson($value, true)
/** set defaults for $example **/
return $example;
}
关于php - 在 laravel 5.3 中使用带访问器的强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231779/