CakePHP 2.3.x数据库事务

mar*_*zak 5 cakephp transactions commit

我需要你帮助使用CakePHP中的事务.

我有一个Product模型,其子句包含Price和Property模型(key product_id).

在我的产品模型中,我添加

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); 
}
Run Code Online (Sandbox Code Playgroud)

在ProductController中,我使用save()来保存我的产品,然后使用我的价格和属性.(我只使用save(),而不是saveAll()).

我的代码是:

$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(); 
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果我在保存价格或属性行中有错误,则仍会添加产品.我原本以为当我有任何错误时,我的行都不会被添加(即回滚会删除它).

我正在使用CakePHP 2.3.8

小智 25

必须是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();
}
Run Code Online (Sandbox Code Playgroud)