2017-09-25 44 views
0

我有兩個表:items_tblrequest_tbl笨我怎樣才能在項目表更新數量字段當用戶提交請求,請求表

items_tbl

| item_id | item_name | quantity | 

request_tbl

| request_id | item_id | quantity_requested | 

request_tbl具有item_id作爲ForeignKey。如何通過$quantity - $quantity_requested更新物料表中的數量字段?當用戶使用codeigniter向請求表提交請求時?

MyController.php

function outward_items($request_id){ 
    $this->load->model('request'); 
    $ord_id = $this->request->insert_request($requests); 
    $outward = array(
     'quantity_left' => $this->input->post('quantity_left'), 
     'item_id'  => $this->input->post('item_id'), 
    ); 
    $cust_id = $this->request->insert_outward($outward); 
    $data['requests'] = $this->request->get_requests($request_id); 
    $data['main_content'] = 'backend/requests/requests'; 
    $data['title'] = 'Outwards'; 
    $this->load->view('includes/template', $data); 
} 
+0

你熟悉的控制器和模型和需要幫助,在短短的SQL查詢? – mrid

+0

是的先生我需要的控制器和模型 – turaco

+0

爲什麼不使用mysql觸發器,這很容易 – Bira

回答

0

INSERT觸發器在MySQL後建立一個,這是一個例子,請創建觸發器這樣的事情。

DELIMITER $$ 
CREATE TRIGGER request_tbl_trigger 
AFTER INSERT ON `request_tbl` FOR EACH ROW 
begin 
    DECLARE id_exists Boolean; 
    -- Check BookingRequest table 
    SELECT 1 
    INTO @id_exists 
    FROM request_tbl 
    WHERE request_tbl.request_id = NEW.request_id ; 

    IF @id_exists = 1 
    THEN 
     UPDATE items_tbl 
     SET quantity = quantity-1 
     WHERE item_id = NEW.item_id; 
    END IF; 
END; 
$$ 
DELIMITER ; 
0
/* requested items and item id */ 
$requested_items = $this->input->post('quantity_left'); 
$item_id   = $this->input->post('item_id'); 

/* subtract from quantity left */ 
$this->db->set('quantity_left', 'quantity_left-'.$requested_items, false); 

/* 
if quantity_left - requested is greater than or equal to zero 
this is to avoid updating of negative number 
for example say quantity_left = 5, requested_items = 7 
5-7 = -2, to avoid this we use below where 
*/ 
$this->db->where("(quantity_left - $requested_items) >= 0" ,NULL, FALSE); 

/* where item_id = item_id */ 
$this->db->where('item_id' , $item_id); 

/* update item_table */ 
$this->db->update('items_tbl');