2014-04-21 46 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 –

相關問題