Eloquent 将十进制转换为字符串

Eloquent casts decimal as string(Eloquent 将十进制转换为字符串)
本文介绍了Eloquent 将十进制转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我的 Eloquent 模型中有一个十进制字段来表示金钱,但在尝试向该字段添加一些数字时,我发现了错误的结果.

经过进一步检查,我发现decimal 字段被转换为字符串,就像 tinker 控制台中的 "1245114.00".

我检查了表结构,可以验证该字段确实是decimal(11,3).

这个问题是之前问过但没有答案.

为什么会这样?

解决方案

您需要在模型中定义哪些字段需要转换为原始属性.

protected $casts = ['my_decimal' =>'漂浮',];

<块引用>

模型上的 $casts 属性提供了一种将属性转换为常见数据类型的便捷方法.$casts 属性应该是一个数组,其中键是要转换的属性的名称,值是您希望将列转换为的类型.支持的转换类型有:integerrealfloatdoublestringbooleanobjectarraycollectiondatedatetime时间戳

这里有一个非常好的解释:

https://mattstauffer.com/blog/laravel-5.0-eloquent-attribute-casting/

文档中也有解释:

https://laravel.com/docs/5.5/eloquent-mutators#属性转换

I have a decimal field to represent money in my Eloquent Model and I'm noticing erroneous results when trying to add some number to this field.

Upon further inspection, I found that the decimal field is being cast as a string, like "1245114.00" in the tinker console.

I checked the table structure and I can verify that the field is indeed decimal(11,3).

This question was asked before but has no answers.

Why is this happening?

解决方案

You need to define in your model which fields need to be cast to a primitive attribute.

protected $casts = [
    'my_decimal' => 'float',
];

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are: integer, real, float, double, string, boolean, object, array, collection, date, datetime, and timestamp

There is a really good explanation here:

https://mattstauffer.com/blog/laravel-5.0-eloquent-attribute-casting/

Also there is an explanation in the docs:

https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting

这篇关于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 的问题)