我有一个大型数据集,在发布到服务器时需要将其写入数据库,但客户端编辑器中的错误可能会添加额外的记录,从而触发“完整性约束违规”。
我的问题是,当我到达数据中触发错误的点时,许多以前的数据已经在数据库中更新了。我需要回滚并拒绝发布的数据。
这是我的 Controller 的操作。
/**
* Handles saving data from the network editor.
*/
public function json_save()
{
if($this->request->is('post'))
{
$result = array();
$data = $this->request->input('json_decode');
if(isset($data->network_id) && !empty($data->network_id))
{
$dataSource = $this->Node->getDataSource();
$dataSource->begin();
$result['nodes'] = $this->updateModel($data->network_id, $this->Node, 'nodes', $data, array(
'ParamValue'
));
$result['connections'] = $this->updateModel($data->network_id, $this->Connection, 'connections', $data);
$dataSource->commit();
$this->viewClass = 'Json';
$this->set('result', $result);
$this->set('_serialize', array(
'result'
));
return;
}
}
throw new ErrorException('Posted data missing.');
}
我的 Controller 的 updateModel
函数对模型 $this->Node
和 $this->Connection
执行一些删除和更新。
如何回滚通常在更新 $this->Connection
模型期间引发的“完整性约束违规”。
我不确定这是否是一个可以捕获然后回滚的 PHP 异常,或者是否有其他方法来捕获它。
最佳答案
你可以做:
$dataSource->begin();
try {
// The queries here.
} catch (Exception $e) {
$dataSource->rollback();
throw $e;
}
$dataSource->commit();
关于php - 抛出数据库错误异常时可以回滚事务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15884108/