We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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.9k
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
}