[英]Laravel Eloquent attribute casting doesn't work
I have a field in my database that stores a decimal
value.我的数据库中有一个存储
decimal
值的字段。 It's defined in my database migration as such:它在我的数据库迁移中定义如下:
$table->decimal('buy_amount', 16, 8)->default(0);
Now reading from the database using Laravel Eloquent it returns a string value instead.现在使用 Laravel Eloquent 从数据库中读取它会返回一个字符串值。 According to the documentation , I tried casting it in the model file using the
$casts
array however it makes no difference . 根据文档,我尝试使用
$casts
数组将其投射到 model 文件中,但没有区别。 It's worth mentioning that every other cast works fine except for decimals.值得一提的是,除了小数之外,其他所有演员都可以正常工作。
protected $casts = [
'buy_amount' => 'decimal:8',
];
This is the result I get:这是我得到的结果:
What am I missing?我错过了什么?
This happens because PHP doesn't have a decimal
type, so the value is converted to a string
(see this Laracasts post )发生这种情况是因为 PHP 没有
decimal
类型,因此该值被转换为string
(请参阅此 Laracasts 帖子)
When casting to a decimal, the asDecimal(...)
function in Illuminate\Database\Eloquent\Concerns\HasAttributes
is called;转换为小数时,调用
Illuminate\Database\Eloquent\Concerns\HasAttributes
中的asDecimal(...)
function; this function uses the native PHP function number_format
, which returns a string .这个 function 使用本机 PHP function
number_format
,它返回一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.