In cakephp 2, you save them in a transactional way 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 would be dependent if any error occurred I'd rollback
reading the documentation of cakephp 3, vi changed the process, but I could not reproduce.
In the code snippet below after saving in the Users model, I want to save the Tokens , but in case of an Tokens error I want do rollback in Users .
For example, the token entity is mandatory to have the field "token", when entering the exception either rollback and not register the user. But when I do Users it is always saved in the database.
$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;
});