Laravel eloquent 模型模型属性转换(我应该转换哪些属性类型?) [英] Laravel eloquent model model attribute casting (Which attribute types should I cast?)

查看:65
本文介绍了Laravel eloquent 模型模型属性转换(我应该转换哪些属性类型?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我是否完全理解 Laravel Eloquent 属性转换.根据文档,(https://laravel.com/docs/8.x/eloquent-mutators#attribute-casting),这些是支持的类型:

I am not sure I fully understand Laravel Eloquent attribute casting. According to documentation, (https://laravel.com/docs/8.x/eloquent-mutators#attribute-casting), these are the supported types:

整数、实数、浮点数、双精度数、十进制数:、字符串、布尔值、对象、数组、集合、日期、日期时间、时间戳、加密、加密:对象、加密:数组和加密:集合

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'
];

我也理解当值存储为整数(0 或其他)时需要将属性转换为布尔值.

I also understand the need for attribute casting to boolean when the values are stored as integers (0 or sth else).

但是对于其他属性类型(例如整数),我应该始终进行属性转换吗?或者只是当数据库中的字段属于不同类型时?有哪些用例或其他属性的最佳实践是什么?

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?)

推荐答案

默认情况下,属性将转换为表中定义的列类型.因此,如果您的列是整数,那么它将被转换为 int.

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.

但是,如果您想为特定字段修改此行为,会发生什么?这就是属性转换进入场景的时候.

But, what happens if you want to modify this behavior for specific fields? That's when attribute casting enters the scene.

例如,假设我们在名为 projects 的表中有一个名为 config 的列,类型为 json,我们可以在其中存储其他配置元素每个项目.

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.

就我而言,能够将这些数据作为 array 处理会很有用.因此,我们无需接收stringobject,而只需处理一个简单的array.为此,我们只需:

In my case, it'd be useful to be able to handle this data as an array. So, instead of receiving a string or object, we can just deal with a simple array. To do this, we just:

class Project extends Model
{
    // ...

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

    // ...
}

这样,每当我们使用 Eloquent 从数据库中获取项目时,每条记录都会将该属性作为 array.而且,当尝试存储/更新记录时,它会被转换回 json.

This way, whenever we use Eloquent to fetch projects from the database, each record will have that property as an array. And also, it will be converted back to json when trying to store/update records.

与您指定的情况有关(将元素保存为 string,然后将其检索为 integer)当然是完全可能的.您需要为该字段设置访问器和修改器.对于名为 number 的属性:

Related to the case you specified (saving element as a string but then retrieve it as an integer) is totally possible of course. You'll need to set both the accessor and the mutator for that field. For an attribute named 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.

这篇关于Laravel eloquent 模型模型属性转换(我应该转换哪些属性类型?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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