You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中DECIMAL类型字段无法更新的问题求助

解决DECIMAL字段无法更新的问题
  • 检查模型批量赋值权限
    确保Customer模型的$fillable数组包含percentage字段,否则批量更新时该字段会被自动过滤:

    class Customer extends Model
    {
        protected $fillable = ['name', 'address', 'phone', 'percentage'];
    }
    
  • 验证数值是否符合DECIMAL(2,2)范围
    DECIMAL(2,2)的取值范围是0.00到0.99,整数部分只能为0。如果输入值是1.00或更大,部分数据库会静默截断为0.99且不报错,看起来像是字段没更新。可以临时把字段改为DECIMAL(4,2)测试,确认数值能正常写入后再调整回合适精度。

  • 排查模型钩子或全局作用域
    检查模型是否有saving、updating等观察者方法,或是全局作用域,这些逻辑可能会修改percentage的值或阻止字段更新:

    // 检查模型中是否存在类似钩子
    public static function boot()
    {
        parent::boot();
        static::updating(function ($customer) {
            // 这里可能修改了percentage或返回false终止更新
        });
    }
    
  • 查看实际执行的SQL语句
    开启Laravel查询日志,确认更新语句是否包含percentage字段:

    DB::enableQueryLog();
    $customer->update([...]);
    dd(DB::getQueryLog());
    

    如果日志里的UPDATE语句没有percentage,就是批量赋值的问题;如果有但数值不对,就检查取值和字段范围。

  • 尝试直接赋值后保存
    避开批量更新方法,直接赋值再保存,测试是否能生效:

    $customer->name = $request->input('name');
    $customer->address = $request->input('address');
    $customer->phone = $request->input('phone');
    $customer->percentage = $request->input('percentage');
    $customer->save();
    

内容的提问来源于stack exchange,提问作者Murphstar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:42:04