首页 > 解决方案 > 更新时更改了 json 类型列的数据结构

问题描述

我有三个 json 列:

class DeliveryCharge extends Model
{
    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
    /**
     * @var string The database table used by the model.
     */
    public $table = 'delivery_charges';

    /**
     * @var array Validation rules
     */
    public $rules = [
    ];
    
    protected $casts = [
     "locations" => "json",
     "location_ids" => "json",
     "time_charges" => "json"
    ];
    public $belongsTo = [

        'districts' => [ 'RainLab\Location\Models\District', 'locations->district_id']
    ];
}

保存数据:

$deliveryCharge->location_ids = $data['location_ids'];
$deliveryCharge->locations = Utility::addLocationId($data['location_ids']);
$deliveryCharge->time_charges = $data['charge_time'];
$deliveryCharge->save();

更新数据:

$data = post();
$deliveryCharge =  DeliveryCharge::find($this->param('id'));
$deliveryCharge->location_ids = $data['location_ids'];
$deliveryCharge->locations = Utility::addLocationId($data['location_ids']);
$deliveryCharge->time_charges = $data['charge_time'];
//echo '<pre>';print_r($data); exit;
$deliveryCharge->update();

检查 $datasaveupdate函数。两者都是 100% 相同的。但是save方法保存数据如下:

[{"charge":"80","max_delay":"2","unit":"1"},{"charge":"50","max_delay":"3","unit":"1"}]

update方法改变数据格式如下:

{"1":{"charge":"80","max_delay":"2","unit":"1"},"2":{"charge":"50","max_delay":"3","unit":"1"}}

任何想法?

标签: laravel

解决方案


我观察到数据是相同的,但数组索引从 1 开始,而不是 0 update。这是主要问题。所以我转换了数组并将起始索引设置为 0。


推荐阅读