【问题标题】:CakePHP 1.3 - Transaction for saving models that aren't relatedCakePHP 1.3 - 保存不相关模型的事务
【发布时间】:2012-09-04 11:42:01
【问题描述】:

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

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

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

这是否可以确保 Dog 和 House 以及 Car 的保存?即事务在哪个模型上启动是否重要?

【问题讨论】:

    标签: cakephp transactions cakephp-1.3


    【解决方案1】:

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

    $continue = true;
    $this->Car->begin();
    
    // Do stuff that might set $continue to false.
    
    if ($continue) {
        $this->Car->commit();
    } else {
        $this->Car->rollback();
    }
    

    要在“做事”位期间设置 $continue,请检查每个保存等。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多