gpt4 book ai didi

php - Laravel 5 Eloquent,如何动态设置 cast 属性

转载 作者:可可西里 更新时间:2023-11-01 00:42:20 28 4
gpt4 key购买 nike

在 laravel 5.1 中有一个叫做属性转换的新特性,这里有详细的记录: http://laravel.com/docs/5.1/eloquent-mutators#attribute-casting

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

例如,我有一个包含列的表:

id | name          | value       | type    |
1 | Test_Array | [somearray] | array |
2 | Test_Boolean | someboolean | boolean |

可以设置 value 属性转换,取决于 type 字段,在写入(创建/更新)和获取中都有效?

最佳答案

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

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

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

更新:

从数据库中读取数据时,上面的代码工作得很好。写入数据时,必须确保类型设置在之前。有 2 个选项:

  1. 始终传递一个属性数组,其中 type 键位于 value 键之前 - 目前模型的 fill() 方法尊重处理数据时的 key 顺序,但这不是面向 future 的。

  2. 在设置其他属性之前明确设置type 属性。使用以下代码可以轻松完成:

    $model == (new Model(['type' => $data['type']))->fill($data)->save();

关于php - Laravel 5 Eloquent,如何动态设置 cast 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31847050/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com