【问题标题】:Laravel Eloquent attribute casting doesn't workLaravel Eloquent 属性转换不起作用
【发布时间】:2021-01-15 19:40:44
【问题描述】:

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

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

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

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

这是我得到的结果:

我错过了什么?

【问题讨论】:

  • 存储价格为int

标签: php laravel casting decimal


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 2014-11-04
    • 2021-02-13
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多