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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?