Laravel 5雄辩,如何动态设置演员表属性 [英] Laravel 5 Eloquent, How to set cast attribute dynamically

查看:66
本文介绍了Laravel 5雄辩,如何动态设置演员表属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In laravel 5.1 there is new feature called Attribute Casting, well documented at here : http://laravel.com/docs/5.1/eloquent-mutators#attribute-casting

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

My question is, it is possible to make attribute casting dynamically ?

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

for example, I have a table with columns :

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

可以设置value属性强制转换,具体取决于type字段,该属性在write(create/update)和fetch吗?

it is possible to set value attribute cast, depends on type field, that work both in write(create/update) and fetch ?

推荐答案

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

You'll need to overwrite Eloquent model's getCastType() method in your model class:

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

您还需要向 $ this-> casts 添加,以便Eloquent将该字段识别为 castable .您可以在此处放置默认的演员表,如果您未设置 type 的话,将使用默认的演员表.

You'll also need to add value to $this->casts so that Eloquent recognizes that field as castable. You can put the default cast there that will be used if you didn't set type.

更新:

当从数据库中读取数据时,上面的方法非常有效.写入数据时,必须确保在之前设置了类型.有2个选项:

The above works perfectly when reading data from the database. When writing data, you have to make sure that type is set before value. There are 2 options:

  1. 始终传递属性数组,其中 type 键在 value 键之前-在模型的 fill()方法方面处理数据时键的顺序,但这不是面向未来的.

  1. Always pass an array of attributes where type key comes before value key - at the moment model's fill() method respects the order of keys when processing data, but it's not future-proof.

明确设置 type 属性,然后再设置其他属性.可以使用以下代码轻松完成此操作:

Explicitely set type attribute before setting other attributes. It can be easily done with the following code:

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

这篇关于Laravel 5雄辩,如何动态设置演员表属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆