获取id的数据,并将其包含在Codeigniter中的update_batch中



我有一个表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

这是我的updatebatch代码。有一个包含id和quantity字段的表单。我计划用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');
}

您需要首先从数据库中获取传递的购物车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');
}

最新更新