【问题标题】: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 值。有没有办法比在访问器和修改器中显式地实现强制转换逻辑更容易?

【问题讨论】:

  • 我对转换属性没有任何经验。但是我知道有类似mutators 的东西。另一个建议是使用events

标签: 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;
}

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 2011-12-14
    • 2023-03-31
    • 2017-01-13
    • 1970-01-01
    • 2016-06-18
    • 2012-11-16
    • 1970-01-01
    相关资源
    最近更新 更多