简体   繁体   English

Laravel eloquent 模型模型属性转换(我应该转换哪些属性类型?)

[英]Laravel eloquent model model attribute casting (Which attribute types should I cast?)

I am not sure I fully understand Laravel Eloquent attribute casting.我不确定我是否完全理解 Laravel Eloquent 属性转换。 According to documentation, ( https://laravel.com/docs/8.x/eloquent-mutators#attribute-casting ), these are the supported types:根据文档( https://laravel.com/docs/8.x/eloquent-mutators#attribute-casting ),这些是支持的类型:

integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, timestamp, encrypted, encrypted:object, encrypted:array, and encrypted:collection整数、实数、浮点数、双精度数、十进制数:、字符串、布尔值、对象、数组、集合、日期、日期时间、时间戳、加密、加密:对象、加密:数组和加密:集合

So far, I've only used date casting on my models (when the fields were stored as timestamps in the db), like this:到目前为止,我只在我的模型上使用了日期转换(当字段作为时间戳存储在数据库中时),如下所示:

protected $dates = [
    'modified_at', 'published_at'
];

I also understand the need for attribute casting to boolean when the values are stored as integers (0 or sth else).我也理解当值存储为整数(0 或其他)时需要将属性转换为布尔值。

But what about other attribute types (integers, for example), should I always do attribute casting?但是对于其他属性类型(例如整数),我应该总是进行属性转换吗? Or just when the field in the database is of a different type?或者只是当数据库中的字段属于不同类型时? What are the use cases or what is the best practice with other attributes?有哪些用例或其他属性的最佳实践是什么?

(I can't, for example, imagine creating a string field in migrations, then saving some number inside it as string and then casting it back into an integer on the model?) (例如,我无法想象在迁移中创建一个字符串字段,然后将其中的一些数字保存为字符串,然后将其转换回模型上的整数?)

By default, attributes will be casted to the type of column defined in the table.默认情况下,属性将转换为表中定义的列类型。 So, if your column is an integer, then it will be casted as int .因此,如果您的列是整数,那么它将被转换为int

But, what happens if you want to modify this behavior for specific fields?但是,如果您想为特定字段修改此行为,会发生什么? That's when attribute casting enters the scene.那是属性转换进入场景的时候。

For example, imagine we have in a table called projects a column named config of type json in which we can store additional configuration elements for each project.例如,假设我们在名为projects的表中有一个名为configjson类型列,我们可以在其中存储每个项目的其他配置元素。

In my case, it'd be useful to be able to handle this data as an array .就我而言,能够将这些数据作为array处理会很有用。 So, instead of receiving a string or object , we can just deal with a simple array .因此,我们可以只处理一个简单的array ,而不是接收stringobject To do this, we just:为此,我们只需:

class Project extends Model
{
    // ...

    protected $casts = [
        'config' => 'array',
    ];

    // ...
}

This way, whenever we use Eloquent to fetch projects from the database, each record will have that property as an array .这样,每当我们使用 Eloquent 从数据库中获取项目时,每条记录都会将该属性作为array And also, it will be converted back to json when trying to store/update records.而且,在尝试存储/更新记录时,它将被转换回json

Related to the case you specified (saving element as a string but then retrieve it as an integer ) is totally possible of course.与您指定的情况相关(将元素保存为string ,然后将其作为integer检索)当然是完全可能的。 You'll need to set both the accessor and the mutator for that field.您需要为该字段设置访问器和修改器。 For an attribute named number :对于名为number的属性:

/**
 * This will be called when fetching the element.
 */
public function getNumberAttribute($value)
{
    return (int)$value;
}

/**
 * This will be called when storing/updating the element.
 */
public function setFirstNameAttribute($value)
{
    $this->attributes['number'] = (string)$value;
}

Now, a reason to ever need to make this?现在,有理由需要这样做吗? Well, you could be dealing with a database not properly well designed, or with a production database that is being used by multiple systems and changes in the db are hard to accomplish.好吧,您可能正在处理设计不当的数据库,或者处理多个系统正在使用的生产数据库,并且数据库中的更改很难完成。 In those cases you could make use of this kind of value manipulation to work as you want in your app.在这些情况下,您可以利用这种值操作在您的应用程序中随心所欲地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM