How can I get a list of all the orders in processing and pending status in Magento 2?
2 Answers
We should use Service Contracts Layer:
class OrderCollectData
{
/**
* @var \Magento\Sales\Api\OrderRepositoryInterface
*/
protected $orderRepository;
/**
* @var \Magento\Framework\Api\SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var \Magento\Framework\Api\FilterBuilder
*/
protected $filterBuilder;
/**
* @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
* @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
* @param \Magento\Framework\Api\FilterBuilder $filterBuilder
*/
public function __construct(
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\Api\FilterBuilder $filterBuilder
) {
$this->orderRepository = $orderRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->filterBuilder = $filterBuilder;
}
public function execute()
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter(
'status',
'processing',
'eq'
)
->addFilter(
'status',
'pending',
'eq'
)->create();
$orders = $this->orderRepository->getList($searchCriteria);
foreach ($orders->getItems() as $order) {
//Your code
};
// Using filterBuilder
$statusProcessingFilter = $this->filterBuilder
->setField('status')
->setConditionType('eq')
->setValue('processing')
->create();
$statusPendingFilter = $this->filterBuilder
->setField('status')
->setConditionType('eq')
->setValue('pending')
->create();
$searchCriteria = $this->searchCriteriaBuilder
->addFilters([$statusProcessingFilter, $statusPendingFilter])
->create();
$orders = $this->orderRepository->getList($searchCriteria);
foreach ($orders as $order) {
// Process each order as needed
}
}
}
Something like this should work
public function __construct(
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
) {
$this->orderCollectionFactory = $orderCollectionFactory;
}
public function getOrderCollection($status)
{
$orderCollection = $this->orderCollectionFactory
->create()
->addAttributeToSelect('*')
->addAttributeToFilter('status', ['eq'=> $status]);
return $orderCollection;
}
So you would call
$this->getOrderCollection('processing')
$this->getOrderCollection('pending')