我有一个表shopping_cart,其中包括:
id | user_id | product_id | quantity | total_price
1 3 4 1
2 3 5 2
3 3 7 2
和products表包括:
product_ id | price |
4 1000
5 2000
7 3000
这是我的update_batch代码。有一个包含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');
}
发布于 2021-07-14 06:47:53
您需要首先从数据库中获取传入购物车ID的产品ID,然后使用此产品ID从products表中获取其价格,然后将价格与数量相乘。下面的代码应该可以工作:
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');
}
https://stackoverflow.com/questions/68371854
复制相似问题