Laravel 5 Eloquent,如何动态设置强制转换属性

ant*_*tra 4 php casting laravel eloquent laravel-5

在 laravel 5.1 中有一个名为 Attribute Casting 的新功能,这里有详细记录:http : //laravel.com/docs/5.1/eloquent-mutators#attribute-casting

我的问题是,可以动态进行属性转换吗?

例如,我有一个带有列的表:

id | name          | value       | type    |
1  | Test_Array    | [somearray] | array   |
2  | Test_Boolean  | someboolean | boolean |
Run Code Online (Sandbox Code Playgroud)

可以设置value属性转换,取决于type字段,在 write(create/update) 和 fetch 中都有效?

jed*_*ylo 5

您需要在模型类中覆盖Eloquent模型的getCastType()方法:

protected function getCastType($key) {
  if ($key == 'value' && !empty($this->type)) {
    return $this->type;
  } else {
    return parent::getCastType($key);
  }
}
Run Code Online (Sandbox Code Playgroud)

您还需要为$this->casts添加,以便 Eloquent 将该字段识别为castable。如果您没有设置type,您可以将默认演员表放在那里。

更新:

从数据库读取数据时,上述方法完美无缺。写入数据时,您必须确保在value之前设置type。有2个选项:

  1. 始终传递类型键在键之前的属性数组- 目前模型的fill()方法在处理数据时尊重键的顺序,但它不是面向未来的。

  2. 在设置其他属性之前显式设置类型属性。可以使用以下代码轻松完成:

    $model == (new Model(['type' => $data['type']))->fill($data)->save();
    
    Run Code Online (Sandbox Code Playgroud)