0

I need to get the collection of orders with the the items ordered by using the customer ID. But I am not getting the items ordered in my collection. Please help.

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $order = $objectManager->create('Magento\Sales\Model\Order')->getCollection()->addAttributeToFilter('customer_id', $captinId)->setOrder('entity_id',$direction)->setPageSize($pageSize)->setCurPage($currentPage);
                $orderResult = $order->getData();
return $orderResult;

2 Answers 2

1

Try the following way:

$captinId = 2;
$direction = 'ASC';
$pageSize = 20;
$currentPage = 1;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderItemCollection = $objectManager->create('Magento\Sales\Model\ResourceModel\Order\Item\Collection')
    ->setOrder('entity_id', $direction)
    ->setPageSize($pageSize)
    ->setCurPage($currentPage);

$orderItemCollection->getSelect()->joinLeft(
    'sales_order',
    'sales_order.entity_id=main_table.order_id',
    ['increment_id']
)->where('sales_order.customer_id=?', $captinId);
$orderResult = $orderItemCollection->getData();

Note: Avoid to use \Magento\Framework\App\ObjectManager::getInstance()

1
  • Thanks for the reponse, now I am getting the products but I want to get them as an array of items. Please help me. Apr 18, 2019 at 9:08
0

Please try the code below.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$lastyear = date('Y-m-d', strtotime("-1 year"));
$orderCollection = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\Collection');
$orderCollection->addAttributeToFilter('customer_id',123456)
            ->addAttributeToFilter('status','complete')
            ->addAttributeToFilter('created_at', array('gteq'  => $lastyear))->load();

echo "<pre>";print_r($orderCollection->getData()); exit;

Then you need to load the order items by order ID.

<?php
$orderid = 2;

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objectManager->create('Magento\Sales\Api\Data\OrderInterface')->load($orderid);

//Loop through each item and fetch data
foreach ($order->getAllItems() as $item)
{
   //fetch whole item information
   print_r($item->getData());

   //Or fetch specific item information
   echo $item->getId();
   echo $item->getProductType();
   echo $item->getQtyOrdered();
   echo $item->getPrice(); 

}
?>
2
  • But this also does not get the order items in my response. Apr 18, 2019 at 7:01
  • I have updated the answer. Apr 18, 2019 at 7:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.