CakePHP 1.3 - 用于保存不相关模型的事务

时间:2012-09-04 11:42:02

标签: cakephp transactions cakephp-1.3

如何在控制器中启动事务,然后尝试保存多个彼此无关的模型?如果有任何失败,显然我希望回滚,如果一切正常则提交。

我想我的问题是我在哪个模型上开始交易?

$datasource = $this->Car->getDataSource();
$datasource->begin($this->Car);

$car = $this->Car->save();
$dog = $this->Dog->save();
$house = $this->House->save();

if ($car && $dog && $house) {
    $datasource->commit($this->Car);
} else {
    $datasource->rollback($this->Car);
}

这是否可以确保狗和房子保存以及汽车?即交易开始的哪个模型是否重要?

1 个答案:

答案 0 :(得分:6)

用于启动事务的模型无关紧要,但通常人们使用与控制器“最接近”的模型(如果有)。

$continue = true;
$this->Car->begin();

// Do stuff that might set $continue to false.

if ($continue) {
    $this->Car->commit();
} else {
    $this->Car->rollback();
}

要在“Do stuff”位中设置$ continue,请检查每次保存等。

if (!$this->Car->save()) {
    $continue = false;
}

if ($continue) {
    if (!$this->Dog->save()) {
        $continue = false;
    }
}

if ($continue) {
    if (!$this->House->save()) {
        $continue = false;
    }
}