简体   繁体   中英

How to use transactions in cakephp?

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'));
    }

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();
}

I think I was able to carry out the transaction with "transactional".

In my tests if there is an error in the Clients entity, then the Users entity is not saved.

I do not know if this is the best way to do, but it's worked

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

        $user = $userTable->newEntity();
        $client = $clientTable->newEntity();
        if ($this->request->is('post')) {
            $request = $this->request->getData();

            $user = $userTable->patchEntity($user, $request);

            $conn = ConnectionManager::get('default');

            try {
                $conn->transactional(function ($conn) use ($userTable, $clientTable, $user, $client, $request) {

                    $userTable->saveOrFail($user, [
                        'atomic' => false
                    ]);
                    $request['user_id'] = $user->id;
                    $client = $clientTable->patchEntity($client, $request);

                    $clientTable->saveOrFail($client, [
                        'atomic' => false
                    ]);
                });
                $this->Flash->success(__('The user has been registered.'));

                return $this->redirect([
                    'action' => 'login'
                ]);
            } catch (\Cake\ORM\Exception\PersistenceFailedException $e) {
                $this->Flash->error(__('Error on save: {0}', $e->getMessage()));

                return $this->redirect([
                    'action' => 'register'
                ]);
            }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM