2012-07-03 19 views
0

我正在使用基於innoDB的數據庫。我如何使用交易來保存數據。我有一個用戶數組。但只保存數據庫中的最後一條記錄。我無法使用saveAll,因爲我必須將數據保存在多個表中,並且它們都是相互關聯的。CakePHP 2.1.3中的事務使用情況

我甚至無法定義模型關聯,因爲我的數據庫中有大量的條目。所以每次加入都會執行。

請建議我如何使用交易概念?

回答

3

所有事務都在當前的DataSource對象上執行。

首先,你需要得到它(模型):

$dataSrc = $this->getDataSource(); 

This method返回當前綁定到模型中的數據源對象。

然後你可以使用DataSource Object's methods開始,提交或回滾transactions

$dataSrc->begin(); 
//Do something 

if (/*Everything is nice?*/) { 
    $dataSrc->commit(); 
} else { 
    //Bad things have happened 
    $dataSrc->rollback(); 
} 

您必須實現自己的當然邏輯。由於Cake 2.2 you can also do real nested transactions。根據Wikipedia A「嵌套事務」是:

A nested transaction occurs when a new transaction is started by an instruction that is already inside an existing transaction. The new transaction is said to be nested within the existing transaction, hence the term. Nested transactions are implemented differently in different databases. However, they have in common that the changes are not made visible to any unrelated transactions until the outermost transaction has committed. This means that a commit in an inner transaction does not necessary persist updates to the database.

當然這一切取決於你使用的數據庫。 MySQL InnoDB transactional storage engine確實支持交易。

而另一澄清迴應此評論:

Yes, I am using $this->Model->saveAll($this->request->data, array('deep' => true) in my controller. This is written under a foreach loop. And only the last foreach record is going to be saved into the database. – Arun Jain

$this->Model->saveAll();並不需要在一個循環中運行!它會爲你「自動」管理事情。把它從循環中取出。 此外,您的問題涉及交易,而不是用saveAll()保存數據。 Model::saveAll()只是saveMany()saveAssociated()的包裝 - 它將根據模型關聯的類型選擇使用哪種方法。

閱讀Cake Book這一切都是很好的解釋有...

+0

當我嘗試使用$ DATASRC = $這個 - >了getDataSource();它給了我一個錯誤:使用未定義的方法。 –

+1

你是否想在其他地方做而不是在**模型**中?沒有其他的情況可以讓你使用未定義的method_錯誤。 –

+0

是的,我在我的控制器中使用$ this-> Model-> saveAll($ this-> request-> data,array('deep'=> true),這是在foreach循環下編寫的,只有最後一個foreach記錄將被保存到數據庫中 –