Magento2 – Get Product ID from Order History

magento2

How we can get the product id from an order history. Below is the code of which I am trying to fetch the product id but it keeps giving me this array error.

Fatal error: Uncaught Error: Call to a member function getProductId() on array:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create("Magento\Customer\Model\Session");
$field  = 'customer_id';
$collection = $this->_orderCollectionFactory->create()->addAttributeToSelect('*')->addFieldToFilter($field, $customerSession->getCustomerId());

foreach ($collection as $_order){
    foreach ($_order->getAllVisibleItems() as $_items) {
        foreach ($_items as $_item) {
            echo $_item->getProductId();                    
        }
    }                   
}

The above issue can be resolved by assigning an array. But still need to know the better way.

Or is there any way to get the items from a customer order history?

Best Answer

Replace

foreach ($_order->getAllVisibleItems() as $_items) {
     foreach ($_items as $_item) {
          echo $_item->getProductId();
     }
}

To

foreach ($_order->getAllVisibleItems() as $_item) {                    
     echo $_item->getProductId();                    
}
Related Topic