1

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?

2 Answers 2

2

Replace

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

To

foreach ($_order->getAllVisibleItems() as $_item) {                    
     echo $_item->getProductId();                    
}
2
  • can you please tell me if there is any way to get the attributes, is it possible something like with $_item->getAttributes()
    – JN_newbie
    Mar 6, 2018 at 10:54
  • Just print_r($_item->getData()); and check. Mar 7, 2018 at 7:31
2

getAllVisibleItems() able to provide of an order product ids.No need extra foreach loop inside

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

Instead of:

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

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.