10

If I have a logic that involve updating multiple model objects which will update a few tables in database, how to provide a database transaction to ensure the data integrity?

19

You are probably saving an aggregate of multiple connected objects. Determine which of these objects is the root, for example:

               [order]              <------ this is the root
               /  |  \
billing_address   |   shipping_address
                  |
            order_items

Add the update logic in the resource model of the root and use a transaction there.

How to use transactions

  1. If you want to save multiple model instances, you can use the transaction model. Inject a transaction factory \Magento\Framework\DB\TransactionFactory in your resource model and use it like this:

    $saveTransaction = $this->transactionFactory->create();
    $saveTransaction->addObject($objectToSave);
    $saveTransaction->addObject($otherObjectToSave);
    ...
    $saveTransaction->save();
    

    Commit or rollback is automatically handled by the save() method.

  2. Alternatively you can use transactions directly (if you use other database updates than $model->save():

    $connection = $this->getConnection();
    $connection->beginTransaction();
    try {
        ...
        $connection->commit();
    } catch (\Exception $e) {
        $connection->rollBack();
        throw $e;
    }
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.