2017-04-08 59 views
0

我有一個名爲'spec'的JSON字段,並且在JSON格式中有大約10個其他項目。我只需要更新數量。更新數據庫中的一個JSON字段 - CodeIgniter

儘管當我嘗試這種方法時,它會刪除其中的所有內容並只設置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); 
+1

你是不是寫回到數組,你基本上覆蓋它。 –

+0

您可以嘗試更新sql而不是選擇sql –

回答

0

您需要overrite只有這一個領域,在查詢更新全部領域。

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

根據不同的數據庫上,最好的解決辦法是使用特定功能ommit更新整個結構 - https://stackoverflow.com/a/34987329/2926214

相關問題