2015-04-14 36 views
1

我需要刪除行和插入數據後,但是這個操作應該被分組在一個事務中。CakePHP 2.6在事務中刪除

我錯了還是atomic => false param不能設置爲Model::delete()

有什麼建議嗎?

+0

原子不支持2.6,但在3.0。 – pbond

+0

是的,它在3.0中可用,但遷移過程並不容易。 – Serginho

+0

我正在查看整個2.6 api,尋找一些在刪除操作中啓動事務的行,至少現在我什麼也沒找到。因此,如果我開始一個事務,刪除行並回滾應該是工作,行不應該被刪除。 – Serginho

回答

3

您可以將您的刪除和插入語句放入transaction。您可以構建檢查以查看刪除和插入是否都成功,如果不是,則回滾事務。所以你會在你的模型中得到類似的東西:

public function deleteAndInsert($deleteId, $newData) { 
    $dataSource = $this->getDataSource(); 
    $dataSource->begin(); 

    if (!$this->delete($deleteId)) { 
     // The delete failed, rollback 
     $dataSource->rollback(); 
     return false; 
    } 

    if (!$this->save($newData)) { 
     // The save failed, rollback 
     $dataSource->rollback(); 
     return false; 
    } 

    // Everything seems to be fine, commit the transaction 
    $dataSource->commit(); 
    return true; 
} 
2

我會擴大Oldskools的答案。雖然它可以正常工作,但它不會給您提供很多機會來報告發生錯誤的位置,或者在返回通用錯誤值之前讓您選擇撤銷其他可能的事情。我會在這裏實現一些異常處理,然後你會有更多的選擇來處理失敗。

public function deleteAndInsert($deleteId, $newData) { 
    $dataSource = $this->getDataSource(); 

    try { 
     $dataSource->begin(); 

     if (!$this->delete($deleteId)) { 
      throw new Exception('Error deleting ID'); 
     } 

     if (!$this->save($newData)) { 
      throw new Exception('Error Storing new data'); 
     } 

     $dataSource->commit(); 
     return 'Action completed successfully'; 

    }catch(Exception $e){ 
     $dataSource->rollback(); 
     return $e->getMessage(); 
    } 
} 
+0

好點,這爲錯誤報告和處理提供了更好的可能性。 +1! – Oldskool