将 $casts 转换为浮点数但只有一位小数

Cast $casts to float but only one decimal place

在我的模型中,我添加了 $casts 字段,因为我需要 Laravel 来给我一个浮动。我的数据库将其存储为字符串。

所以我在我的模型中做了这个 Score.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Score extends Model
{
    protected $fillable = [
        'value', 'comment'
    ];

    protected $casts = [
        'user_id' => 'int',
        'value' => 'float'
    ];

太棒了,投了。然而,它的小数位太多了。我只需要小数点后一位,到十分之一。

我的 json 端点数据如下所示:

{
    "id": 2,
    "name": "Zed",
    "avatar_path": null,
    "score": {
        "id": 2,
        "value": 9.9000000000000003552713678800500929355621337890625,
        "comment": null,
        "user_id": 2,
        "created_at": "2018-05-03 07:03:37",
        "updated_at": "2018-05-03 07:03:41"
    }
},

我希望 9.9...... 只是 9.9 这可能吗?

在我的架构中,我是否正确地将其创建为 $table->decimal('value', 3, 1):

    Schema::create('scores', function (Blueprint $table) {
        $table->increments('id');
        $table->decimal('value', 3, 1)->nullable(); //////// is this correct?

创建一个 mutator/accessor 怎么样?

在您的模型中添加

public function getValueAttribute($value) {
    return round($value, 1);
}

有关更多信息,请访问相关的 Laravel docs

如果您 100% 确定只需要一位小数,那么数据库方法也不错,但这样您可以存储原始值以供将来使用,并且仍然以当前所需的格式响应