1

How to add filter last past one-hour completed orders collection in Magento 2?

  $searchCriteria = $this->searchCriteriaBuilder
        ->addFilter('is_process', $isprocess)
        ->addSortOrder($this->sortBuilder->setField('entity_id')
            ->setAscendingDirection()->create())
        ->setPageSize(3)->setCurrentPage(1)->create();

    $fromDate = date('Y-m-d H:i:s', strtotime('-1 hour'));
    $toDate = date('Y-m-d H:i:s');

    $ordersList = $this->orderRepository->getList($searchCriteria);
    $ordersList->addFieldToFilter('created_at', array('from' => $fromDate, 'to' => $toDate));

    return $ordersList;
1

2 Answers 2

2

here's a shorter version to build the time filter:

// get current time - 1 hour
$time = date(
    "Y-m-d H:i:s",
    (time() - 3600)
);

// then use it as a filter
(...)
->addFieldToFilter(
   'created_at',
   [
      'gteq' => $time
   ]
);

as for the status filtering, it should be something like this:

->addFieldToFilter(
    'status',
    [
        'eq' => 'complete'
    ]
);
0

Works for me

$searchCriteria = $this->searchCriteriaBuilder
             ->addFilter('is_reward_process', $isrewardprocess)
             ->addSortOrder($this->sortBuilder->setField('entity_id')
             ->setAscendingDirection()->create())
             ->setPageSize(50)->setCurrentPage(1)->create();
    
   $ordersList = $this->orderRepository->getList($searchCriteria);
         
   $ordersList->getSelect()->where(
                    new \Zend_Db_Expr('TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, `created_at`)) >= ' . $canceltime * 60 * 60)
                );
    
    return $ordersList;
3
  • hmm ok, so let me get something checked first, the way I understood the problem and also how this evolved in your answer as well, you are extracting the orders created within an hour and completed in between. is this what you need? or is it that you need to identify which orders were marked as complete within the last hour?
    – Diana
    Commented Feb 2, 2021 at 11:48
  • it's ok .... Thanks a lot @DianaBotean
    – Devidas
    Commented Feb 2, 2021 at 11:54
  • you're welcome :)
    – Diana
    Commented Feb 2, 2021 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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