Magento – Magento2 Correct Way to get Order items

cartmagento-2.0.2magento2orders

I am working on M2 Payment Extension our merchant need us to send items details along with order

Everything works fine but $order->getAllItems(); or $order->getAllVisibleItems(); returning simple and configurable parent products so

if I have 2 products in Cart

  • 1 Simple Product
  • 1 Associated of configurable product

so instead of getting two products I am getting three ; one simple , associated product and its parent product;

I can try to extract correct products but I am sure it must be some other

    /** @var \Magento\Sales\Model\Order $order */
    $order = $payment->getOrder();
    /**
     * Get All Items of Products
     */
    $productItems = $order->getAllItems() // returning 3 products where I have 2 in cart 
    $productItemsTest = $order->getAllVisibleItems(); // returning 3 products where I have 2 in cart 

Best Answer

This is how the different methods to get items from an order work:

  • getItems(): returns array of items from loaded order item collection
  • getAllItems(): returns array of all items that are not marked as deleted
  • getAllVisibleItems(): returns array of all items that are not marked as deleted and do not have a parent item

So to get only the configurable product and not its associated product, getAllVisibleItems() is the correct method:

  • the single simple item does not have a parent => visible
  • the configurable item does not have a parent => visible
  • the associated simple item has a parent => not visible

Note that unfortunately, as of only getItems() is part of the service contract in Magento\Sales\Api\Data\OrderInterface