Laravel Eloquent 属性转换无效

Laravel Eloquent attribute casting doesn't work

我的数据库中有一个存储 decimal 值的字段。它在我的数据库迁移中定义如下:

$table->decimal('buy_amount', 16, 8)->default(0);

现在使用 Laravel Eloquent 从数据库读取它 returns 一个字符串值。 According to the documentation,我尝试使用 $casts 数组将其投射到模型文件中,但它没有区别。值得一提的是,除小数点外,其他所有演员都可以正常工作。

protected $casts = [
    'buy_amount' => 'decimal:8',
];

这是我得到的结果:

我错过了什么?

发生这种情况是因为 PHP 没有 decimal 类型,因此该值被转换为 string(参见 this Laracasts post

转换为小数时,调用Illuminate\Database\Eloquent\Concerns\HasAttributes中的asDecimal(...)函数;此函数使用本机 PHP 函数 number_formatwhich returns a string.