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?

1 Answer 1


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

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();

    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();
    try {
    } catch (\Exception $e) {
        throw $e;
  • Is there any supported way to save mutiple objects while using repositories? They internally calls save() methods of resource models, so each of them will be saved in separate transactions. Repositories often contain some validation logic, so it is generally recommended to use them instead of plain resource model save() methods. Commented Sep 27, 2019 at 8:29
  • 1
    @BartoszKubicki there is. If two resource models use the same connection (which they usually do, the default one) saving the relation in the afterSave() of the first resource will cause queries to be added to the same transaction. Look into how orders are saved, line by line. OrderRepository::save() is the entrypoint. Commented Nov 14, 2019 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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