PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 5, 2022

[FIXED] How to use transactions in cakephp?

 January 05, 2022     cakephp, cakephp-3.0, commit, php, transactions     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing