How to get the items orders by the customer in the order collection?
-
26-02-2021 - |
Question
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;
Solution
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()
OTHER TIPS
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();
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange