In magento1, We are using below code to get the total orders by a customer

$customer = Mage::getSingleton('customer/session')->getCustomer();
$orders = Mage::getResourceModel('sales/order_collection')->addFieldToSelect('*')->addFieldToFilter('customer_id', $customer->getId());
echo $orders->getSize();

How to get same in magento2 ?. Any help would be appreciated.I want get this on order success page with using Object manager.


You can use the below code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
    $customerId = $customerSession->getCustomer()->getId();

    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');

    $connection = $resource->getConnection();
    $select     = $connection->select()
        ->from($resource->getTableName('sales_order'), 'COUNT(*)')
        ->where('customer_id=?', $customerId);

    $totalOrderCount = (int) $connection->fetchOne($select);

Try this..


    protected $_orderFactory;

    public function __construct(
     \Magento\Sales\Model\OrderFactory $orderFactory) {
     $this->_orderFactory = $orderFactory;

    // Customer email as a parementer of method
    public function getOrders($customerEmail)
     //Retrieve all orders with this email address
     $orders = $this->_orderFactory->create()
      ->addFieldToFilter('customer_email', $customerEmail);

     //Retrieve all order ids
     $orderIds = $order->getAllIds();
  • Hi,It will also work but My need was using Object manager Directly.Thanks For help. – akgola Sep 19 '17 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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