CakePHP 3 - How to do rollback

1

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;
    });
    
asked by anonymous 13.12.2016 / 21:12

1 answer

1

I was sabotaged by MySql Workbench.

It generated tables with the MyISAM engine that does not support rollback, even though it is marked InnoDB.

Solving this worked.

    
21.12.2016 / 18:31