1
In cakephp 2 in birds transactional with $data_source->begin();
,$data_source->commit();
, or $data_source->rollback();
.
So when I needed to insert into more than one table, and the data was dependent if any error occurred I did the rollback
reading the cakephp 3 documentation, I saw it changed the process, but I couldn’t reproduce.
In the code snippet below after saving to the model Users, I want to save the Tokens, but if an error occurs in the Tokens I want to rollback in Users.
for example, the Tokens entity is required to have the "token" field, when entering Exception wants to rollback and not register the User in the database. But when I do Users is always saved in the bank.
$connection = ConnectionManager::get('default');
$return = $connection->transactional(function ($connection) use($json) {
try {
$obj = $this->Users->newEntity();
$obj = $this->Users->patchEntity($obj, $json);
$User = $this->Users->save($obj);
//$token["token"] = $json["google_token"];//forçando erro
$token["user_id"] = $User->id;
$obj = $this->Tokens->newEntity();
$obj = $this->Tokens->patchEntity($obj, $token);
$Token = $this->Tokens->save($obj);
$return["success"] = true;
$return["message"] = "Cadastrado com sucesso";
$return["data"] = $User;
//fazer o commit
} catch (\Exception $e) {
$return["success"] = false;
$return["data"] = $e->getMessage();
$return["message"] = "Falha ao cadastrar ";
//fazer o rollback
}
return $return;
});