2013-08-03 14 views
5

CakePHPでトランザクションを使用して助けが必要です。CakePHP 2.3.xデータベーストランザクション

私は、PriceモデルとPropertyモデル(key_product_id)にhasManyという節を持つProductモデルを持っています。私の製品モデルで

、私は

function begin() { 
    $db =& ConnectionManager::getDataSource($this->useDbConfig); 
    $db->begin($this); 
} 

function commit() { 
    $db =& ConnectionManager::getDataSource($this->useDbConfig); 
    $db->commit($this); 
} 
function rollback() 
{ 
    $db =& ConnectionManager::getDataSource($this->useDbConfig); 
    $db->rollback($this); 
} 

を追加し、ProductControllerに私は私のプロダクトを保存し、その後、私の価格とプロパティにsave()を使用します。 (私はsaveAll()ではなくsave()のみを使用します)。

私のコードは次のとおりです。

$this->Product->begin(); 
$error = false; 
if($this->Product->save($data) 
{ 
    //my functions and calculations 
    if(!$this->Price->save($data_one) 
    { 
     $error = true; 
    } 
    //calculations 
    if(!$this>Property->save($my_data) 
    { 
     $error = true; 
    } 
} 
if($error) { 
    $this->Product->rollback(); 
} 
else 
{ 
    $this->Product->commit(); 
} 

問題は、私が保存価格またはプロパティの列内のエラーを持っている場合、製品はまだ追加されていることです。エラーが発生した場合は、行が追加されない(ロールバックすると削除されない)と考えていました。私は、CakePHP 2.3.8

答えて

22

テーブルを使用しています

のInnoDB形式でなければなりません。テーブルのMyISAMフォーマットはトランザクションをサポートしていません。

モデルにコードを追加する必要はありません。

ProductController:

$datasource = $this->Product->getDataSource(); 
try { 
    $datasource->begin(); 
    if(!$this->Product->save($data) 
     throw new Exception(); 

    if(!$this->Price->save($data_one) 
     throw new Exception(); 

    if(!$this->Property->save($my_data) 
     throw new Exception(); 

    $datasource->commit(); 
} catch(Exception $e) { 
    $datasource->rollback(); 
} 
+0

こんにちは、しかし、mysqlはInnoDBテーブルと取引 http://dev.mysql.com/doc/refman/5.0/en/commit.html –

+0

@MarceloAymoneをサポートしています。そのにコンテキスト、彼は** MyISAM **を意味します。そして、それは 'フォーマット'ではなく '**エンジン**'と呼ばれなければなりません! – Tuanitim

+0

InnoDbテーブルでトランザクションは自動的に使用されませんか? –

関連する問題