我的 MySQL 表中有一个 TEXT 列,我想用一个 JSON 对象作为字符串填充它,这样我就可以为每行保存的条目定义一些选项。
我只有一个选项,所以我只显示一个复选框,值为1
. 现在提交表单时,我通过请求验证输入。为了确保始终有一个可用的值,我检查输入是否存在(记住它是一个复选框),如果不存在,我用设置为的选项预填充它0
。但是当我查看 phpMyAdmin 时,旧值仍然存在。
这里是代码示例 - 我从来都不擅长用英语解释我自己:P
形式
<label for="dedication" style="font-weight: normal;"><input id="dedication" type="checkbox" name="fields[dedication]" value="1" /> Dedication</label>
请求::all() 覆盖
public function all() {
// get input
$input = parent::all();
// save empty array if fields not set
if (!isset($input['fields'])) {
$input['fields'] = array("dedication" => "0");
}
$this->replace($input);
// dd(parent::all());
return parent::all();
}
模型
protected $table = 'products';
protected $primaryKey = 'id';
// public $timestamps = false;
protected $guarded = ['id'];
protected $fillable = ['product', 'description', 'price', 'campaign_id', 'quantity', 'fields'];
protected $hidden = ['created_at', 'updated_at'];
// protected $dates = [];
protected $casts = ['fields' => 'array'];
例子
假设我创建了一个产品,并且不选中该复选框,那么该产品在列中dedication
的值被保存。通缉的是。NULL
fields
{"dedication": "0"}
当我现在更新此条目并选中dedication
复选框时,它可以工作。值为{"dedication": "1"}
。
现在,如果我再次更新条目,并且未选中该复选框,则该fields
列不会被覆盖,因此旧值仍然存在。
如何更新此列的值?