We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Phalcon ORM getReadConnection Transactions

First of all sorry for my English..

I want to use transactions.

I have some code

$User = new User();

$transaction = new Transaction($this->getDI(), true);

$User->setTransaction($transaction);

//User Model have a method like : 

class User {
//...

    public function cashPlus($amount, $userId = false)
    {
        $userId = ($userId == false) ? $this->id : $userId;

        $query = "UPDATE {$this->getSource()} SET cash = cash + {$amount} WHERE id = {$userId}";

        $this->getReadConnection()->query($query);

        //There can be manipulations  with other Entity, that used same transaction
    }
}

If I set the transaction, will method 'getReadConnection()' use it or not?



98.8k
Accepted
answer

Change the method to:

public function cashPlus($amount, $userId = false)
{
        $userId = ($userId == false) ? $this->id : $userId;

        $query = "UPDATE {$this->getSource()} SET cash = cash + {$amount} WHERE id = {$userId}";

        if (!$this->_transaction) {
            $this->getWriteConnection()->query($query);
        } else {
            $this->_transaction->getConnection()->->query($query);
        }

        //There can be manipulations  with other Entity, that used same transaction
}