gpt4 book ai didi

php - Eloquent 将小数转换为字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:51:44 24 4
gpt4 key购买 nike

在我的 Eloquent 模型中,我有一个小数字段来表示钱,我在尝试向该字段添加一些数字时注意到错误的结果。

经过进一步检查,我发现小数字段被转换为字符串,比如 Tinker 控制台中的 "1245114.00"

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

这个问题是 asked before但没有答案。

为什么会这样?

最佳答案

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

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

这里有一个很好的解释:

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

文档中也有解释:

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

关于php - Eloquent 将小数转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48288519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com