【问题标题】:Update One JSON Field in Database - CodeIgniter更新数据库中的一个 JSON 字段 - CodeIgniter
【发布时间】:2017-09-04 00:04:44
【问题描述】:

我有一个名为“spec”的 JSON 字段,其中还有大约 10 个 JSON 格式的其他项目。我只需要更新数量。

虽然当我尝试这种方法时,它会删除其中的所有其他内容,并且只设置规格 = 数量。

这是我目前所拥有的。

$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);

【问题讨论】:

  • 你不是把它写回数组,你基本上是在覆盖它。
  • 你可以尝试更新sql而不是select sql

标签: php json codeigniter


【解决方案1】:

您只需要覆盖这一个字段并更新查询中的整个字段。

<?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

【讨论】:

    猜你喜欢
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    相关资源
    最近更新 更多