我想在多个模型/表的多个插入/更新查询中使用事务。
在cakephp3 documentation中有一个使用连接管理器 execute()
方法的事务示例,但我必须使用cakephp3的save()
方法进行事务处理。我使用save()
方法尝试了它,但它没有用。有一个SQL错误,它执行所有查询和保存数据,除了sql错误的查询,回滚没有工作!
我的代码就像 -
$connection = ConnectionManager::get('default');
$connection->transactional(function ($connection) use($inputs, $status) {
$serviceTbl = $this->Service;
$service = $serviceTbl->newEntity();
$service->name = $inputs['name'];
$service = $serviceTbl->save($service);
if($service)
{
$this->loadModel('SrvApiClientInfo');
$SrvApiClientInfo = $this->SrvApiClientInfo;
$SrvApiClient = $SrvApiClientInfo->newEntity();
$SrvApiClient->client_name = $inputs['basic_info']['client_name'];
$SrvApiClient->organization_name = $inputs['basic_info']['vendor_name'];
$SrvApiClient->address = $inputs['basic_info']['address'];
$SrvApiClient->email = $inputs['basic_info']['email'];
$SrvApiClient->mobile = $inputs['basic_info']['mobile'];
$SrvApiClient->phone = $inputs['basic_info']['phone'];
$SrvApiClient->fax = $inputs['basic_info']['fax'];
$SrvApiClient->emergency_contact_name = $inputs['basic_info']['emergency_contact_name'];
$SrvApiClient->emergency_contact_mobile = $inputs['basic_info']['emergency_contact_mobile'];
$SrvApiClient->emergency_contact_designation = $inputs['basic_info']['emergency_contact_designation'];
$SrvApiClient = $SrvApiClientInfo->save($SrvApiClient);
if($SrvApiClient){
$this->loadModel('ServiceApiRegistration');
$tblServiceApiRegistration = $this->ServiceApiRegistration;
foreach($inputs['method'] as $method)
{
$ServiceApiRegistration = $tblServiceApiRegistration->newEntity();
$ServiceApiRegistration->service_id = $service['service_id'];
$ServiceApiRegistration->service_api_id = $method;
$ServiceApiRegistration->client_id = $SrvApiClient['client_id'];
$ServiceApiRegistration->status_id = $status['Inactive'];
$tblServiceApiRegistration->save($ServiceApiRegistration);
}
}
}
});
答案 0 :(得分:1)
检查您更密切关联的文档,尤其是“事务方法将执行以下操作”列表中的第3点和第4点
交易方法将执行以下操作:
[...]
- 如果闭包引发异常,则会发出回滚。将重新抛出原始异常。
- 如果闭包返回false,则会发出回滚。
您的代码既不返回false
,也不会在出现错误时抛出异常,因此不会发回回。
如果确实存在SQL“错误”,即在核心中触发了异常,则它应该已被事务包装器捕获,并且应该已发出回滚。所以我怀疑,无论是,没有例外,或者不支持回滚,或者驱动程序认为它们不是。