Magento 2 - Get orders that were completed x days ago
-
13-01-2021 - |
Question
I'm trying to get all orders that were completed a certain number of days ago using the below code:
protected $searchCriteria;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteria,
\Magento\Framework\Api\SortOrderBuilder $sortBuilder
)
{
$this->orderRepository = $orderRepository;
$this->searchCriteriaBuilder = $searchCriteria;
$this->sortBuilder = $sortBuilder;
return parent::__construct($context);
}
public function execute()
{
$today = date("Y-m-d 0:0:0");
$from = strtotime('-3 day', strtotime($today));
$to = strtotime('-2 day', strtotime($today));
$from = date('Y-m-d h:i:s', $from);
$to = date('Y-m-d h:i:s', $to);
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('status','complete','eq')
->addSortOrder($this->sortBuilder->setField('entity_id')
->setDescendingDirection()->create())
->setPageSize(500)->setCurrentPage(1)->create();
$ordersList = $this->orderRepository->getList($searchCriteria);
$ordersList->addFieldToFilter('updated_at', array('from'=>$from, 'to'=>$to));
foreach ($ordersList as $order) {
echo $order->getCustomerEmail();
exit;
}
}
This returns a collection of orders however restricting the date just does not seem to be working at all. What is going wrong here?
Solution
This seems to work:
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('status','complete','eq')
->addFilter('updated_at',$from,'gteq')
->addFilter('updated_at',$to,'lteq')
->addSortOrder($this->sortBuilder->setField('entity_id')
->setDescendingDirection()->create())
->setPageSize(500)->setCurrentPage(1)->create();
So I just updated the initial serach criteria adding the conditions within there. Also then removed the filter on the order repository as was not working that way for me.
OTHER TIPS
You can get extract time to changes to Complete status,you should check sales_order_status_history
.
At the table, sales_order_status_history
Magento save order status changes over time.
SELECT * FROM
sales_flat_order_status_history
where status="complete" and entity_id=4 order by created_at asc limit 1;