我想更新购物车when the item is already in the cart
的数量并添加 when it is not(added in the cart)
。我很困惑如何解决这个问题的扭曲。我谷歌有很多相同的问题,但没有相同的问题/解决方案。
以下是视图的代码:
<?php if($lab): ?>
<table class="table table-striped">
<tr>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php foreach($lab as $rows): ?>
<tr>
<td><?php echo $rows->ldesc; ?></td>
<td><?php echo $rows->lprice; ?></td>
<td><button value="<?php echo $rows->lid; ?>" class="btn btn-info addlabtype"><i class="icon-plus"></i></button></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<script type="text/javascript" >
(function(){
$(document).on('click','.addlabtype',function(){
var id= $(this).val(),
dataString = "id=" + id;
$.ajax({
type:"POST",
url: base_url + "inpatient/addlab",
data:dataString,
success:function(data){
$('.pickedlab').html(data);
}
})
});
})()
</script>
这是我的控制器:
public function addlab(){
$data['cart'] = $this->inpatient_model->addlab();
$this->load->view('admin/addeddiag',$data);
}
这是我的模型:
public function addlab(){
$this->db->select('*');
$this->db->from('lab');
$this->db->where('lid',$this->input->post('id'));
$q = $this->db->get();
$lab = $q->result_array();
$cart = $this->cart->contents();
if($cart){
foreach($cart as $items){
if($this->input->post('id') == $items['id'] ){
$this->cart->update(array(
'rowid' => $items['rowid'],
'qty' => $items['qty'] + 1
));
}else{
$data = array(
'id' => $lab[0]['lid'],
'name' => $lab[0]['ldesc'],
'qty' => 1,
'price' => $lab[0]['lprice']
);
$this->cart->insert($data);
}
}
}else{
$data = array(
'id' => $lab[0]['lid'],
'name' => $lab[0]['ldesc'],
'qty' => 1,
'price' => $lab[0]['lprice']
);
$this->cart->insert($data);
}
return $this->cart->contents();
}
并且是我的代码中出现的一个问题是模型中的 foreach 。我真的不知道如何解决它。因为当我尝试点击.addlabtype
时,我的购物车中有3件商品,当我尝试更新时,除非是我在购物车中添加的最后一件商品,否则不会更新。
对不起我的英语不好。提前谢谢!
修改:
总结一下,如何才能获得购物车中特定rowid
的{{1}}?
答案 0 :(得分:0)
最后问题解决了我只需用以下内容更改模型的值:
$this->db->select('*');
$this->db->from('lab');
$this->db->where('lid',$this->input->post('id'));
$q = $this->db->get();
$lab = $q->result_array();
$cart = $this->cart->contents();
$found = false;
foreach($cart as $items){
if($this->input->post('id') == $items['id'] ){
$this->cart->update(array(
'rowid' => $items['rowid'],
'qty' => $items['qty'] + 1
));
$found = true;
}
}
if($found == false){
$data = array(
'id' => $lab[0]['lid'],
'name' => $lab[0]['ldesc'],
'qty' => 1,
'price' => $lab[0]['lprice']
);
$this->cart->insert($data);
}
return $this->cart->contents();