当我使用CI购物车类创建购物车时,它首先将产品添加到购物车1然后当我将该产品添加到购物车时,下次还添加1个产品而不是2。
我想这样做,当有人将商品添加到购物车时,购物车中的数量会增加,并且购物车中已有相同的商品。
答案 0 :(得分:4)
如果你可以发布一些代码或你发送给购物车类的数据会有所帮助,但这应该指向正确的方向:
function add_cart_item(){
$data = $_POST;
$id = $data['product_id']; //get new product id
$qty = $data['quantity']; //get quantity if that item
$cart = $this->cart->contents(); //get all items in the cart
$exists = false; //lets say that the new item we're adding is not in the cart
$rowid = '';
foreach($cart as $item){
if($item['id'] == $id) //if the item we're adding is in cart add up those two quantities
{
$exists = true;
$rowid = $item['rowid'];
$qty = $item['qty'] + $qty;
}
}
if($exists)
{
$this->cart_model->update_item($rowid, $qty);
echo 'true'; // For ajax calls if javascript is enabled, return true, so the cart gets updated
}
else
{
if($this->cart_model->add_cart_item() == TRUE)
{
echo 'true'; // for ajax calls if javascript is enabled, return true, so the cart gets updated
}
}
}
在cart_model中你可以更新并添加看起来像这样的函数
function update_item($rowid, $qty){
// Create an array with the products rowid's and quantities.
$data = array(
'rowid' => $rowid,
'qty' => $qty
);
// Update the cart with the new information
$this->cart->update($data);
}
// Add an item to the cart
function add_cart_item(){
$id = $this->input->post('product_id'); // Assign posted product_id to $id
$qty = $this->input->post('quantity'); // Assign posted quantity to $cty
//$img = $this->input->post('image'); // Assign posted quantity to $img
$this->db->where('id', $id); // Select where id matches the posted id
$query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1
// Check if a row has been found
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $row->price,
'name' => $row->name,
//'options' => array('image' => $img),
);
$this->cart->insert($data);
return TRUE;
}
// Nothing found! Return FALSE!
}else{
return FALSE;
}
}