我有一个大数据集,发布到服务器时需要将其写入数据库,但是有可能在客户端编辑器中添加了一个错误,这些额外的记录会触发“违反完整性约束”的额外记录。
我的问题是,当我到达数据中触发错误的位置时,那么很多先前的数据已经在数据库中进行了更新。我需要回滚并拒绝发布的数据。
这是我的控制器的动作。
/**
* 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.');
}
我的控制器的
updateModel
函数对模型$this->Node
和$this->Connection
进行一些删除和更新。如何回退通常在更新
$this->Connection
模型期间抛出的“完整性约束违规”。我不确定这是否是我可以捕获的PHP异常,然后进行回滚,或者是否有其他捕获方法。
最佳答案
您可以执行以下操作:
$dataSource->begin();
try {
// The queries here.
} catch (Exception $e) {
$dataSource->rollback();
throw $e;
}
$dataSource->commit();