dongque8332 2018-01-16 19:29
浏览 120
已采纳

Eloquent将十进制转换为字符串

I have a decimal field for money in my model and I am 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?

  • 写回答

3条回答 默认 最新

  • dongxian3574 2018-01-16 19:34
    关注

    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, and timestamp

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料