gpt4 book ai didi

cakephp - CakePHP 是否支持跨多个模型的事务?

转载 作者:行者123 更新时间:2023-12-04 04:29:32 27 4
gpt4 key购买 nike

我正在编写一个支持多种测量单位的应用程序。在极少数情况下,用户想要更改他们的测量系统,我需要运行一个查询,该查询应用乘数将应用程序中的每个单位列缩放到正确的测量系统。为了确保所有数据在此操作出现问题时保持正常,我需要在事务中运行查询。

Cake 是否可以执行包含覆盖多个模型的查询的事务?

到目前为止我找到的只有 DataSource::begin/commit/rollback() ,但这仅支持针对单个模型的查询。

最佳答案

是的,它确实。我在我的应用程序模型中有这个,使交易变得容易。

https://github.com/infinitas/infinitas/blob/dev/Model/AppModel.php#L677

    /**
* @brief wrapper for transactions
*
* Allow you to easily call transactions manually if you need to do saving
* of lots of data, or just nested relations etc.
*
* @code
* // start a transaction
* $this->transaction();
*
* // rollback if things are wrong (undo)
* $this->transaction(false);
*
* // commit the sql if all is good
* $this->transaction(true);
* @endcode
*
* @access public
*
* @param mixed $action what the command should do
*
* @return see the methods for tranasactions in cakephp dbo
*/
public function transaction($action = null) {
$this->__dataSource = $this->getDataSource();
$return = false;
if($action === null) {
$return = $this->__dataSource->begin($this);
} else if($action === true) {
$return = $this->__dataSource->commit($this);
} else if($action === false) {
$return = $this->__dataSource->rollback($this);
}
return $return;
}

那么你可以做这样的事情:
$saved = true;
$this->transaction();
$saved = $saved && $this->save($data);
$saved = $saved && $this->SomeOtherModel->save($data2);
$saved = $saved && $this->AnotherModel->save($data3);

if($saved){
$this->transaction(true);
return $this->id;
}
$this->transaction(false);
return false;

您还可以执行更复杂的操作,例如:
function save1(){

$saved = true;
$this->transaction();
$saved = $saved && $this->save($data);
$saved = $saved && $this->save2($data);


if($saved){
$this->transaction(true);
return $this->id;
}

$this->transaction(false);
return false;
}

cake 不支持嵌套事务,但你可以伪造它们
// this will use transactions if its called directly, but will allow a calling method to // create and manage the transaction.
function save2($data){
$saved = true;
$transaction = $this->transaction(); // will only be true if not already started
$saved = $saved && $this->save($data);

if($transaction){ // if it was started here, finish it
if($saved){
$this->transaction(true);
return true;
}

$this->transaction(false);
return false;
}

return $saved; // return just the status so the other model will finish the transaction
}

为了清楚起见,您可以执行 ClassRegistry::init('SomeRandomModel')->save2() 之类的操作。交易不限于当前模型或相关模型。它适用于任何型号。

关于cakephp - CakePHP 是否支持跨多个模型的事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7235644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com