2011-08-08 35 views
1

我需要做多個插入/更新,所以我想出事務回滾,如果出現任何問題。另外,如果已經存在,我的應用程序應該更新記錄,如果不存在,則插入。Codeigniter:mysql事務和affected_rows

所以首先我嘗試更新記錄使用唯一的ID,如果它返回affected_rows = 0我繼續wih插入。

也許我錯過了事務/受影響的行內的東西,它總是返回affected_rows = 0。

下面是代碼:

$this->db->trans_start(); 

    $this->db->where('order_id', $order_id); 
    $this->db->where('order_status', '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(); 
} 

提前感謝!

回答

2

我使用MySQL的ON DUPLICATE KEY UPDATE來處理這種情況。然而,CodeIgniter的ActiveRecord的實現不支持這個本身,而在這個線程接受的答案:

How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?

好像是死了。所以,請考慮使用原始MySQL而不是ActiveRecord模式;這在CI開發人員中相當普遍(我不使用他們的AR實現)。

+0

感謝您的幫助凱爾!死線可以在這裏訪問:[鏈接](http://web.archive.org/web/20090221091226/http://codeigniter.com/forums/viewthread/80958/)。無論如何,直接查詢的竅門,所以我會用這個解決方案!但是如果我想要ON DUPLICATE KEY UPDATE只在某些行上運行,例如WHERE foo ='1'? – Luciano

+1

對條件陳述沒有線索,抱歉。 –