Codeigniter当用户向请求表提交请求时,如何更新项目表中的数量字段

时间:2017-09-25 07:11:09

标签: mysql codeigniter

我有两个表:items_tblrequest_tbl

items_tbl

| item_id | item_name | quantity |

request_tbl

| request_id | item_id | quantity_requested |

request_tblitem_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); 
}

2 个答案:

答案 0 :(得分:0)

在MySQL中创建一个AFTER 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 ;

答案 1 :(得分: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');