7

how to get order collection in custom module ? like My Orders collection in customers dashboard (frontend). this collection how to get?

7

Refer the following function:

Class : Magento\Sales\Block\Order\History

 /**
     * @return bool|\Magento\Sales\Model\ResourceModel\Order\Collection
     */
    public function getOrders()
    {
        if (!($customerId = $this->_customerSession->getCustomerId())) {
            return false;
        }
        if (!$this->orders) {
            $this->orders = $this->getOrderCollectionFactory()->create($customerId)->addFieldToSelect(
                '*'
            )->addFieldToFilter(
                'status',
                ['in' => $this->_orderConfig->getVisibleOnFrontStatuses()]
            )->setOrder(
                'created_at',
                'desc'
            );
        }
        return $this->orders;
    }

If have any issues. Please comment. I will try to resolve.

  • how to get attribute value from order details ? because I want to get order collection by filtration of custom attribute. – Ishu Feb 18 '17 at 13:34
  • @Ishu: I don't have a solution for this new requirement, as sales order resource models are bit complex. I suggest to post this new question so that others may help you on it. – Pankaj Bhope Feb 19 '17 at 2:58
12

You can used this code in your custom module.

<?php
namespace 'YOUR_CUSTOM_NAME_SPACE';

class YOURCALSS extends \Magento\Framework\App\Action\Action
{

    protected $_orderCollectionFactory;

    public function __construct(
        Magento\Framework\App\Action\Context $context,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory 
    ) {
        $this->_orderCollectionFactory = $orderCollectionFactory;
        parent::__construct($context);

    }

    }
   public function YOURFUNCTION()
   {
       $collection = $this->_orderCollectionFactory->create()->addAttributeToSelect('*')->addFieldToFilter($field, $condition);
    }


   }       
}
  • Thank you very much @Vasoya it is working and useful for many developers and good job bro.. – Nagaraju K Jun 22 '17 at 7:32
6

Note: When I first came across this question, I was just beginning and I couldn't understand how to use the above answers in my code. That's why I'm writing this answer as a reference to any beginner who comes across this question like me.

Here is how I managed to get all orders in the past 3 days that have their statuses as 'pending'

<?php
namespace <Your Namespace Here>;
use \Psr\Log\LoggerInterface;

class Test {
    protected $logger;
    protected $orderRepository;
    protected $searchCriteriaBuilder;


    public function __construct(
        LoggerInterface $logger,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
    ) {
        $this->logger = $logger;
        $this->orderRepository = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    public function execute() {
        $date = (new \DateTime())->modify('-3 day');

        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter(
                'status',
                'pending',
                'eq'
            )->addFilter(
                'created_at',
                $date->format('Y-m-d'),
                'gt'
            )->create();

        $orders = $this->orderRepository->getList($searchCriteria);
        foreach ($orders->getItems() as $order) {
            //Your Code Here
            $this->logger->info("Order# {$order->getIncrementId()} - Creation Date: {$order->getCreatedAt()}");
        }
    }

}
  • Wondering if this way is better from using the collection.. pros/cons ? – Alex Apr 19 '18 at 15:40
  • pros : still working after Magento upgrades – Franck Garnier Oct 22 '18 at 10:02
2
<?php
namespace CustomAPI\MyRecentOrder\Model;
use CustomAPI\MyRecentOrder\Api\MyRecentOrderInterface;

//use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as productCollectionFactory;
//use Magento\Catalog\Api\ProductRepositoryInterface as productRepository;
class MyRecentOrder implements MyRecentOrderInterface 
{
    //protected $logger;
    protected $orderRepository;
    protected $searchCriteriaBuilder;



    public function __construct(
        \Psr\Log\LoggerInterface $logger,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder



        ) 
        {
        $this->logger = $logger;
        $this->_orderRepository = $orderRepository;
        $this->_searchCriteriaBuilder = $searchCriteriaBuilder;


        }

    public function getMyRecentOrder($email,$pagesize,$curpage){

        try{
           $searchCriteria = $this->_searchCriteriaBuilder
            ->addFilter(
                'status',
                'pending',
                'eq'
            )->addFilter(
                'customer_email',
                 $email
            )->create();

            $orders = $this->_orderRepository->getList($searchCriteria)
                       ->addAttributeToSelect('entity_id')
                       ->addAttributeToSelect('created_at')
                       ->addAttributeToSelect('grand_total')
                       ->addAttributeToSelect('status')
                       ->setPageSize($pagesize)
                       ->setCurPage($curpage);
            return $orders->getData();

            }     

                  catch(\Exception $e){
                  $this->logger->info($e->getMessage());
                  return false;
        }

    }
}

//

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.