I need to do multiple insert/update so i came up with transaction to roll back if anything goes wrong. Besides, my application should update the record if already exists, and insert if not.
So first of all i try to update a record using a unique id, if it return affected_rows=0 i continue wih insert.
Probably i miss something within transaction/affected rows, it always return affected_rows=0.
Below is the code:
$this->db->trans_start();
$this->db->where('order_id', $order_id);
$this->db->where('order_sta开发者_Python百科tus', 'Active');
$this->db->update('orders', $order);
$this->db->where('order_id', $order_id);
$this->db->where('sku', $item_sku);
$this->db->update('order_items', $order_items);
$this->db->trans_complete();
if ($this->db->affected_rows()==0){
$this->db->trans_start();
$this->db->insert('orders', $order);
$this->db->insert('order_items', $order_items);
$this->db->trans_complete();
}
Thanks in advance!
I use MySQL's ON DUPLICATE KEY UPDATE
to handle that case. However, CodeIgniter's ActiveRecord implementation does not support this natively, and the accepted answer in this thread:
How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?
Seems to be dead. So, consider just using raw MySQL instead of the ActiveRecord pattern; this is fairly common amongst CI developers (I do not use their implementation of AR).
精彩评论