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

Laravel eloquent model model attribute casting (Which attribute types should I cast?)(Laravel eloquent 模型模型属性转换(我应该转换哪些属性类型?))
本文介绍了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 模型模型属性转换(我应该转换哪些属性类型?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)