我有一个名为'spec'的JSON字段,其中大约有10个其他项目采用JSON格式。我只需要更新数量。
虽然当我尝试这种方法时,它会删除其中的所有其他内容,并设置spec = quantity。
到目前为止我所拥有的。
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
foreach ($coupon_array as $row) {
$spec = json_decode($row['spec'], true);
}
$quantity_new = $spec['quantity'] - 1;
$data2 = array(
'spec' => json_encode(array(
'quantity'=> $quantity_new
)));
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $data2);
答案 0 :(得分:0)
您只需覆盖此一个字段并更新查询中的整个字段。
<?php
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
// i don't know what you're using, but using foreach to extract single row isn't good solution. Look for sth like result_row() maybe.
$coupon = $coupon_array[0];
$spec = json_decode($coupon, true);
$new_quantity = $spec['quantity'] - 1;
$spec['quantity'] = $new_quantity;
$new_spec = json_encode($spec);
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $new_spec);
根据数据库的不同,最佳解决方案是使用特定功能来省略更新整个结构 - https://stackoverflow.com/a/34987329/2926214