In this post I am going to explain how to get customer order collection by customer id in Magento 2.
Using below code snippet you can get customer order data by passing customer id.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | protected $_orderCollectionFactory; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory, array $data = [] ) { $this->_orderCollectionFactory = $orderCollectionFactory; parent::__construct($context, $data); } public function getCustomerOrderCollection($customerId) { $collection = array(); if($customerId > ) { $collection = $this->_orderCollectionFactory->create()->addFieldToFilter('customer_id', $customerId); } return $collection; } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Customer Id $customerId = 1; $orders = $block->getCustomerOrderCollection($customerId); //print all orders echo "<pre>"; print_r($orders->getData()); echo "</pre>"; foreach ($orders as $order) { $orderId = $order->getId(); $subtotal = $order->getSubtotal(); } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $customerId = 1; $orderCollectionFactory = $objectManager->get('Magento\Sales\Model\ResourceModel\Order\CollectionFactory'); $orders = $orderCollectionFactory->create()->addFieldToFilter('customer_id', $customerId); //print all orders echo "<pre>"; print_r($orders->getData()); echo "</pre>"; foreach ($orders as $order) { $orderId = $order->getId(); $subtotal = $order->getSubtotal(); } |
Leave a Reply