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

What does $autoBegin mean?

In Phalcon\Mvc\Model\Transaction\Manager, there is a method get with a parameter $autoBegin, when should I use true/false?



98.9k

When $autoBegin is true it will start the transaction immediately aka. $connection->begin(), when it's false you have to manually begin the transaction after getting the transaction.



2.1k
edited Jul '14
    $order = Orders::findFirstById($id);
    $order->status = 1;
    $trans = $di->get('transactionManager')->get();
    try {
      $trans->begin() // Is `manually begin` like this? 
      $order->setTransaction($trans);
      if($order->update()) {
          $trans->rollback('order save error');
      }
      $log = new Log();
      $log->setTransaction($trans);
      if ($log->create()) {
          $trans->rollback('log save error');
      }

      $trans->commit();
    } catch (Exception $e) {
       //do some other work.
    }

When I use $trans->begin(), the order will not gonna be updated, why? Do I make mistakes?

In this case, $trans->commit() do not work.



98.9k
Accepted
answer
edited Jul '14

You don't have to call manually begin since this is the default behavior:

$order = Orders::findFirstById($id);
$order->status = 1;
$trans = $di->get('transactionManager')->get();
try {

    $order->setTransaction($trans);
    if($order->update()) {
        $trans->rollback('order save error');
    }

    $log = new Log();
    $log->setTransaction($trans);
    if ($log->create()) {
        $trans->rollback('log save error');
    }

    $trans->commit();
} catch (Exception $e) {
    //do some other work.
}

https://docs.phalcon.io/en/latest/reference/models.html#isolated-transactions



2.1k
edited Jul '14

Thank you for your reply. It's working when I use default behavior. I just want to figure out the difference between default behavior and manually behavior. And when should I use begin manually.