简体   繁体   中英

Passing result from Model to Controller dependant on result in Codeigniter

Can't get my head around the best way to do this - I have a model that is adding a product to a shopping cart;

$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();

What is the best way to returning a message to the controller so that i can display to the user that the item has been added/there is not enough stock?

I've read i can use "return" - but as i'm using return $this->cart->contents(); at the bottom of the function I'm not sure where to go.

I'm probably looking at this the complete wrong way, but if anybody could tell me the best way to handle this situation I'd be very grateful.

C.

Try something like this:

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

And, in your controller, just take out the elements as you need, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM