2014-04-21 30 views
0

无法让我的脑袋围绕最好的方式来做到这一点 - 我有一个模型,即将产品添加到购物车;从模型到控制器的传递结果取决于Codeigniter的结果

$this->db->select('*'); 
$this->db->from('products'); 
$this->db->where('product_id',$pid); 
$query = $this->db->get();  
$products = $query->result_array();  
$stock = $products['0']['stock']; 
$quantity = 2; 

$cart = $this->cart->contents(); 
$found = false; 

foreach($cart as $items) 
{        
    if($pid == $items['id'] ){ 

     if ($items['qty'] + $quantity <= $stock){ 
      $this->cart->update(array(
       'rowid' => $items['rowid'], 
       'qty' => $items['qty'] + $quantity 
       ));  
      $found = true;  
      $SEND MESSAGE SAYING ADDED TO CART 
     } 
     else { 
      $found = true;  
      $SEND MESSAGE SAYING NOT ENOUGH STOCK 
     }    
    }   
} 
if($found == false){ 
    $data = array(
       'id' => $products[0]['product_id'], 
       'name' => $products[0]['name'], 
       'qty' => $quantity, 
       'price' => $products[0]['price'] 
       ); 
    if ($quantity <= $stock) 
    { 
     $this->cart->insert($data); 
    } 
    else { 
     echo "Not enough stock"; 
    } 

} 

return $this->cart->contents(); 

什么是返回一个消息给控制器,这样我可以显示该项目已被添加的用户的最佳方式/没有足够的股票?我已阅读我可以使用“返回” - 但正如我使用返回$ this-> cart-> contents();在函数的底部,我不确定要去哪里。

我可能在看这个完全错误的方式,但如果有人能告诉我处理这种情况的最好方法,我会非常感激。

C.

回答

1

尝试这样:

$data   = array(); 
$data['cart'] = $this->cart->contents(); 
$data['msg'] = 'Your message here'; 
return $data; 

而且,在你的控制器,只需取出的元素,因为你需要,如:

$return = $this->model->function(); //your model return here $return 
$cart = $return['cart'];   //cart contents 
$msg = $return['msg'];   //the message added from the model 
+0

辉煌,绝对现货上。非常感谢:-) –

+0

Happie帮助...:D @CarlBembridge –

相关问题