問題描述
我的 Eloquent 模型中有一個十進制字段來表示金錢,但在嘗試向該字段添加一些數字時,我發現了錯誤的結果.
經過進一步檢查,我發現decimal 字段被轉換為字符串,就像 tinker 控制臺中的 "1245114.00"
.
我檢查了表結構,可以驗證該字段確實是decimal(11,3)
.
這個問題是之前問過但沒有答案.
為什么會這樣?
您需要在模型中定義哪些字段需要轉換為原始屬性.
protected $casts = ['my_decimal' =>'漂浮',];
<塊引用>
模型上的 $casts
屬性提供了一種將屬性轉換為常見數據類型的便捷方法.$casts
屬性應該是一個數組,其中鍵是要轉換的屬性的名稱,值是您希望將列轉換為的類型.支持的轉換類型有:integer
、real
、float
、double
、string
、boolean
、object
、array
、collection
、date
、datetime
和 時間戳
這里有一個非常好的解釋:
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
, andtimestamp
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 將十進制轉換為字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!