If you need to perform multiple database operations, then in all most case you need to ensure that everything operation is ok, for do that we should be use database transactions. Let take example below

The Employee have table look like following

CREATE TABLE `employee` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `job_title` varchar(100) DEFAULT NULL,
  `salary` double DEFAULT NULL,
  `notes` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And Telephone look like

CREATE TABLE `telephone` (
  `id` int NOT NULL AUTO_INCREMENT,
  `employee_id` int DEFAULT NULL,
  `type` varchar(20) NOT NULL,
  `no` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

How can we create a new employee and telephone action the right way? This can be achieved in three ways using transactions:

  • Manual transactions

  • Implicit transactions

  • Isolated transactions

Let take step by step case above

A manual transactions example

<?php Class EmployeeController extends Phalcon\Mvc\Controller
{
    public function saveAction()
    {
        $this->db->begin();

        //block 1
        $employee = new Employee();
        $employee->name = 'Phalcon';
        $employee->job_title = 'Full time';

        if(!$employee->save()) {
            $this->db->rollback();
            return;
        }

        //block 2
        $telephone = new Telephone();
        $telephone->employee_id = 9; //maybe 1 or anything
        $telephone->type = 'mobile';

        if(!$telephone->save()) {
            $this->db->rollback();
            return;
        }
        //Commit the transaction
        $this->db->commit();
    }
}

When running these two block, think that first one fails and second one succeeds. Then telephone table will have a row that refers to an employee with ID 9 that doesn’t exist.

If we ran these two block in a Phalcon Model transaction, if the first statement fails then the second statement will be rolled back making no changes. That is result we are expected

To see Implicit Transactions and Isolated Transaction take look at https://docs.phalconphp.com/en/latest/reference/model-transactions.html#implicit-transactions