【问题标题】:CakePHP 2.3.x database transactionCakePHP 2.3.x 数据库事务
【发布时间】:2013-08-04 15:32:01
【问题描述】:

我需要您在 CakePHP 中使用事务的帮助。

我有一个 Product 模型,带有子句 hasMany 到 Price 和 Property 模型(关键 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); 
}

在 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(); 
}

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

我使用的是 CakePHP 2.3.8

【问题讨论】:

    标签: cakephp transactions commit


    【解决方案1】:

    表格必须是 InnoDb 格式。 MyISAM 格式的表不支持事务。

    无需在模型中插入额外的代码。

    产品控制器:

    $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();
    }
    

    【讨论】:

    • 嗨,但是,mysql 支持 InnoDb 表和事务dev.mysql.com/doc/refman/5.0/en/commit.html
    • @MarceloAymone:在这种情况下,他的意思是 MyISAM。这必须称为“引擎”,而不是“格式”!
    • InnoDb 表中不会自动使用事务吗?
    猜你喜欢
    • 2011-08-12
    • 2011-10-05
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多