2017-09-25 11 views
0

私は2つのテーブルを持っているCodeIgniterの

| request_id | item_id | quantity_requested | 

request_tblはForeignKeyとしてitem_idを持っています。 $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

これは一例であり、MySQLではINSERTトリガーの作成後、このようなトリガーなものを作成してください。

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');