Almost every post I read states that I should be working on objects using Magento 2 repositories rather that instantiating objects using Magento 2 object factories.

That's what I started to do, and all was great until I wrote an small extension to programatically create a shipment whilst also writing a comment to the orders history table.

I would have expected to do something like this in a database transaction, so if there's a failure everything gets rolled back, but I just can't see how to use database transactions with repositories.

If I do something like

$order = $this->orderRepository->get($orderId);


$transaction = $this->transactionFactory->create();


I get a warning in phpStorm of: Expected \Magento\Framwork\Abstract\Model, got \Magento\Sales\Api\Data\OrderInterface. Basically it looks like the database transaction object is expecting factory generated Models rather than repository generated objects. Does that mean that repositories don't actually support database transactions?

1 Answer 1


This is completely my opinion but I think M2 2.0 was released too soon and there were many inconsistencies in approach.

But it was a huge task to convert M1 without losing all the logic and lessons learnt. First there was the object manager. Useful in testing . Then generally speaking factory methods as they were direct ports of M1 logic. Completely logical. Why reinvent the wheel? Then came the principal of repositories (among other things i.e. search criteria). Generally they exist for most entities and work but not in all cases. And here we are today (with other concepts View models). Code is now more verbose but in theory should require minor adjustment as we move through further major releases.

The point I'm making is that I've learnt in M2 there are always exceptions to the rule. Some things work in areas but not in others. But mainly because the framework has evolved so much through the major releases.

That said take a look at my shipment console script and helper.



I think that's doing what you are trying to do. But maybe I misunderstand.

  • The question was more about the use of database transactions with repository objects. When saving to 2 or more separate tables I would normally do this using a database transaction object by adding the objects that needed saving to it and then calling the save method on the database transaction object to ensure that the changes got committed together. However in the new world the repository is now responsible for saving the repository objects, and I'm not sure where database transactions fit in.
    – Mark H
    Sep 30, 2019 at 10:35

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.