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?


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;

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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