I need to get the order id by increment id. I would normally do this by calling the order factory:

/* Magento\Sales\Model\OrderFactory */
$order = $this->_orderFactory->loadByIncrementId($incrementId);
$orderId = $order->getId();

However, in this particular class I'm already using the order collection class:

public function __construct(
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
$this->orderCollectionFactory = $orderCollectionFactory;

So I could use the collection to get what I need and return only the first item:

$orderId = $orderCollectionFactory->create()
  ->addFieldToFilter('increment_id', $incrementId)

So now I'm wondering: which way is the fastest? the model factory will load the whole order object data, which is a bit redundant since I only need the order id. The collection will return only the data I need for the only order that match (because I asked for the first item only) and I would not need to use another class

PS: I know there are API and we should use those whenever we can. Unfortunately I cannot use them in this instance so they are not an option in this case.


As you already said, loading the order object is overkill. Not only do you get a lot of data, but there may be plugins that can do some additional work and take time.

The collection only gets what you want, but there is also a trap. The getFirstItem() function only gets what you want, but behind the scenes, the collection will, in fact, load all the orders.

To work around this, you want to use the paging system that is built-in in the collections.

$orderId = $this->orderCollectionFactory->create()
               ->addFieldToFilter('increment_id', $incrementId)

However, nothing stops you from creating a custom resource model that will perform the most straightforward query to get you what you want.

See for example Temando\Shipping\Model\ResourceModel\Order::getIdByExtOrderId()

  • thank you so much for your reply, I totally forgot about paging system! – Lou Nik Dec 28 '20 at 8:22

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.