2

I'm learning Magento 2 and got a headache while trying to find how to get all orders from customer.

With Magento 1.x, we can get all orders from customer with the below code.

$yourCustomerId = '123123';
$field          = 'customer_id';
$collection     = Mage::getModel("sales/order")->getCollection()
                   ->addAttributeToSelect('*')
                   ->addFieldToFilter($field, $yourCustomerId);

Anyone out there can please show me the correct way in 2.x version?

UPDATED:

I want to get the orders from customer (Magento\Customer\Model\Data\Customer) event observer.

  • Where you tried to call this code? – Amit Bera Apr 12 '16 at 7:52
  • @AmitBera I've just edit the question. Please take a look. – Toan Nguyen Apr 12 '16 at 7:57
7

As per as,magento2 standard,At __construct() function of yours block class/model class/Controller class you need to inject Sales Collection Factory class,Then Filter that collection by Customer id.

protected $_orderCollectionFactory;
protected $orders;
public function __construct(
    .....
            \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
           .......
        ) {
    ...
    $this->_orderCollectionFactory = $orderCollectionFactory;
    ........
    parent::__construct($context, $data);
}


public function getOrders()
{

    if (!$this->orders) {
        $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect(
            '*'
        )->addFieldToFilter(
            'customer_id',
            $customerId
        )->setOrder(
            'created_at',
            'desc'
        );
    }
    return $this->orders;
}

if you try to use this at block clals then at your block class's phtml file ,you can call the Order collection by $orderCollection = $block->getOrders();

  • Is there anyway to do this without using \Magento\Sales\Model\ResourceModel\Order\CollectionFactory ? Can we just simple use the Order model? I want to get orders from customer (Magento\Customer\Model\Data\Customer) event observer. – Toan Nguyen Apr 12 '16 at 8:01
  • wait,you will reply you – Amit Bera Apr 12 '16 at 8:08
  • Doesn't the __construct is missing context and a data-array? – Max Mar 29 '17 at 12:31

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.