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

时间:2022-10-16 00:23:31

How do I start a transaction in a controller, then attempt to save multiple models that have no relation to each other? If anything fails, obviously I wish to rollback, and if everything worked then commit.

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

I guess my question is which model do I start the transaction on?

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

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

Will this work to ensure Dog and House save as well as the Car? i.e. Does it matter which model the transaction is started on?

这项工作是否可以确保狗和房子保存以及汽车?即交易是以哪种模式开始的?

1 个解决方案

#1


6  

It doesn't matter which model you use to start the transaction, but generally people use the model "closest" to the controller if there is one.

使用哪种模型来启动事务并不重要,但通常人们会使用与控制器“最接近”的模型(如果有的话)。

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

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

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

To set $continue during the "Do stuff" bit, check each save etc.

要在“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;
    }
}

#1


6  

It doesn't matter which model you use to start the transaction, but generally people use the model "closest" to the controller if there is one.

使用哪种模型来启动事务并不重要,但通常人们会使用与控制器“最接近”的模型(如果有的话)。

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

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

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

To set $continue during the "Do stuff" bit, check each save etc.

要在“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;
    }
}