【问题标题】:get data of id and include in update_batch in Codeigniter获取 id 的数据并包含在 Codeigniter 的 update_batch 中
【发布时间】:2021-09-23 01:34:23
【问题描述】:

我有一张表 shopping_cart,其中包括:

id | user_id | product_id | quantity | total_price
1    3         4            1         
2    3         5            2        
3    3         7            2

产品表包括:

   product_ id | price |
    4            1000
    5            2000
    7            3000

这是我的 update_batch 代码。有一个带有 id 和数量字段的表单。我打算通过 id 获取产品价格,然后将其乘以数量,然后将结果设置为 total_price 。我搜索了答案,但它们都不起作用。我怎样才能做到这一点?

public function updateCart($data)
  {

    for($i=0;$i < count($data['id']);$i++)
    {
    
      $batch[] = array('id' => $data['id'][$i],
              'quantity' => $data['quantity'][$i]
              );
    }

    $this->db->update_batch($this->table , $batch ,'id');
  }

【问题讨论】:

    标签: php sql codeigniter


    【解决方案1】:

    您需要首先从数据库中获取传递的购物车 ID 的产品 ID,然后使用此产品 ID 从产品表中获取其价格,然后将价格乘以数量。以下应该有效:

    public function updateCart($data)
      {
    
        for($i=0;$i < count($data['id']);$i++)
        {
    
          // select the product ID
          $this->db->select('product_id')->from('shopping_cart');
          $this->db->where('id',$data['id'][$id]);
          $query = $this->db->get();
          $productID = $query->row_array()['product_id'];
    
          // now select the cost of the item from DB
          $this->db->where('id',$productID);
          $this->db->select('price')->from('products');
          $query = $this->db->get();
          $productPrice = $query->row_array()['price'];
    
          // now calculate your total as:
          $total = $productPrice * $data['quantity'][$i];
    
          // and include it on the array as:
          $batch[] = array('id' => $data['id'][$i],
                  'quantity' => $data['quantity'][$i],'total_price' => $total
                  );
        }
    
        $this->db->update_batch($this->table , $batch ,'id');
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      相关资源
      最近更新 更多