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

Database transaction cross different connections

Is that possible?

try { start tran;

$this->db1->execute(sql1); $this->db2->execute(sql2);

commit tran; } catch (Exception $e) { rollback tran; throw $e; } finally { do_clean_up(); }

No. As far as the database is concerned, those two connections are two entirely different people. A transaction being started is a query that runs on that connection and will have no affect on your other connections. Only that connection will have the transaction started.

If you want to have the query on connection 1 be rolled back if the query on connection 2 fails, you're going to have to watch for that and manually roll back.



29.1k

I saw this, does it work?

$manager = new \Phalcon\Mvc\Model\Transaction\Manager();

 $manager->setDbService("vs_hotel");
 $tran1 = $manager->get();

 $manager->setDbService("vs_common");
 $tran2 = $manager->get();

 $pointModel = new PointModel();
 $pointModel->setTransaction($tran2);
 $pointModel->name = "ttt";
 $pointModel->position = "[122, 3432]";
 $pointModel->city_id = 323;
 $pointModel->city_py = "hello";

 if($pointModel->save() == false) {
     foreach($pointModel->getMessages() as $message) {
         echo $message->__toString() . PHP_EOL;
     }
     $manager->rollback();
 }

 $eqsModel = new EQSModel();
 $eqsModel->setTransaction($tran1);
 $eqsModel->out_id = "343";
 $eqsModel->entity_id = 3343;
 $eqsModel->vendors = "[fdfd]";

 if($eqsModel->save() == false) {
     foreach($eqsModel->getMessages() as $message) {
         echo $message->__toString() . PHP_EOL;
     }
     echo "=====---eqs rollback---======\n";
     $manager->rollback();
 }
$manager->commit();