php - 在 laravel 5.3 中使用带访问器的强制转换

标签 php json laravel casting

我想使用 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/

相关文章:

php - 如何在 Laravel 本地化文件中使用 HTML 标签?

php - 更大、更少或者更小、更多的查询?

php - 上传文件过程中不会导致服务器端错误

php - 如何解决文件意外结束错误?

使用 JSON 将 JavaScript 转为 Java

php - laravel 中的 {{asset ('css/app.css' )}} 与 {{mix ('css/app.css' )}} 相同吗

Laravel - whereHas() 中关系的最新记录

php - 此应用程序中的不安全内容错误

javascript - html 表格转 json - 修改单元格

c# - “JSON”未定义