问题描述
我在Eloquent模型中有一个十进制字段来表示货币,并且尝试在此字段中添加一些数字时会注意到错误的结果.
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.
进一步检查后,我发现小数字段被转换为字符串,就像修补程序控制台中的"1245114.00"
.
Upon further inspection, I found that the decimal field is being cast as a string,like "1245114.00"
in the tinker console.
我检查了表结构,并且可以验证该字段确实是decimal(11,3)
.
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.
为什么会这样?
推荐答案
您需要在模型中定义哪些字段必须转换为原始属性.
You need to define in your model which fields need to be cast to a primitive attribute.
protected $casts = [
'my_decimal' => 'float',
];
这里有一个很好的解释:
There is a really good explanation here:
https://mattstauffer.com/blog/laravel-5.0-eloquent -attribute-casting/
文档中也有一个解释:
https://laravel.com/docs/5.5/eloquent-mutators#属性广播
这篇关于雄辩地将小数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!