Wednesday, January 5, 2022

[FIXED] How to use transactions in cakephp?

Issue

I'm trying to use commit with setConnection() but it doesn't work... I have no idea how to make the transaction work in cakephp

I found in the documentation this: https://book.cakephp.org/3.0/en/orm/database-basics.html#using-transactions

but I could not implement... The problem is that I want to guarantee the save of two entities:

$this->Users->save($user) and $clientTable->save($client)

this is my code:

public function register()
    {
        $locator = TableRegistry::getTableLocator();
        $clientTable = $locator->get("Clients");

        $user = $this->Users->newEntity();
        $client = $clientTable->newEntity();

        if ($this->request->is('post')) {

            $request = $this->request->getData();

            $user = $this->Users->patchEntity($user, $request);

            $result = false;
            // begin()
            if ($this->Users->save($user)) {
                $request['user_id'] = $user->id;
                $client = $clientTable->patchEntity($client, $request);
                if ($clientTable->save($client)) {
                    $result = true;
                }
            }
            if ($result) {
                // commit()
                $this->Flash->success(__('The user has been registered.'));

                return $this->redirect([
                    'action' => 'login'
                ]);
            } else {
                // rollback()
            }

        $this->Flash->error(__('The user could not be registered. Please, try again.'));
        }
        $this->set(compact('$user'));
    }


Solution

You can try the following code:

try {
    $this->Users->getConnection()->begin();
    $this->Users->saveOrFail($userEntity, ['atomic' => false]);
    $this->Users->getConnection()->commit();

} catch(\Cake\ORM\Exception\PersistenceFailedException $e) {
    $this->Users->getConnection()->rollback();
}


Answered By - Dhananjay Kyada

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.