【问题标题】:Using casts with accessor in laravel 5.3在 laravel 5.3 中使用带有访问器的强制转换
【发布时间】:2017-07-03 01:48:01
【问题描述】:
我想使用 laravel (5.3) eloquent 的 $casts 属性,如 protected $casts = ["example" => "object"] 和 getExampleAttribute 访问器,但似乎访问器丢弃了 $casts 行为。这对我来说至关重要,因为我想将 JSON 对象存储在数据库中并为其设置默认值,例如:
public function getExampleAttribute($value) {
if($value === NULL)
return new \stdclass();
return $value
}
所以我永远不会在我的视图中得到 NULL 值。有没有办法比在访问器和修改器中显式地实现强制转换逻辑更容易?
【问题讨论】:
标签:
php
json
laravel
casting
【解决方案1】:
如果您希望该字段明确遵循$casts 定义,则以下解决方案有效。您只需要从访问器突变器内部手动调用强制转换函数:
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;
}