Hello Magento Folks,
Having thousands of orders inside your Magento 2 store makes it difficult to find particular order information. Isn’t it? Several times it happens to you when you are looking for desired information that isn’t possible to look at using the default backend search.
For example, you have one customer email id and you want to know how many orders are placed inside your Magento 2 store using that particular email by your registered customer.
We, Magicians, believe that nothing is impossible, so we came up with one super-duper script that will allow you to fetch all orders programmatically. But keep in mind that this script will only help you to fetch registered customer’s orders, not for guest customers. To do the same, we need to specify the customer order id and customer id to get all the details of a particular order.
<?php namespace VENDOR\EXTENSION\Block; use Magento\Backend\Block\Template\Context; use Magento\Framework\Event\ObserverInterface; class Ordersfromemail extends \Magento\Framework\View\Element\Template { protected $resourceConnection; protected $customerSes; protected $ordersales; public function __construct(Context $context, \Magento\Framework\App\ResourceConnection $resourceConnection, \Magento\Customer\Model\Session $customerSes, \Magento\Sales\Model\Order $ordersales) { $this->resourceConnection = $resourceConnection; $this->customerSession = $customerSes; $this->orderSales = $ordersales; parent::__construct($context); } public function getCustomerOrderCollection() { $connection = $this->resourceConnection->getConnection(); $customerSession = $this->customerSession->create(); if ($customerSession->isLoggedIn()) { $customer_email = $customerSession->getCustomer()->getEmail(); $order_collection = $this->$ordersales->create()->getCollection()->addAttributeToFilter('customer_email', $customer_email); foreach ($order_collection as $order) { echo "Order Id: ". $order->getEntityId(); echo "Customer Id: ".$order->getCustomerId(); } } } } </pre>
That’s it! Simply create one file that contains above code in your root folder and simply access the file by navigating through URL. You are free to play and manipulate this according to your need for finding records.<br ?–>
That’s it for today, Let us know if you are facing an issue while implementing using this code by commenting below.
Happy Coding!