0

I have a cron job to execute some tasks over new orders. The cron job is executing perfectly. But facing an issue with the below code snippet.

Below logs are printing in system.log except the log statement in foreach. Getting query results when I am executing the MySQL statement from getSelect().

Then why its not looping through foreach ?

class ProcessPendingorders
{
        protected $_logger;
        protected $_orderCollectionFactory;
        protected $_date;


        public function __construct(

                \Psr\Log\LoggerInterface $logger,
                \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
                \Magento\Framework\Stdlib\DateTime\TimezoneInterface $date


        ) {

                $this->_logger                          = $logger;
                $this->_orderCollectionFactory          = $orderCollectionFactory;
                $this->_date                            = $date;
        }

        public function execute()
        {

                $this->_logger->info("Orders Start - ");

                $current_date   = $this->_date->date()->format('Y-m-d H:i:s');

                $start_date     = strtotime($current_date) - 10000;
                $start_date  = date("Y-m-d H:i:s",$start_date);

                $orders = $this->_orderCollectionFactory->create()->addAttributeToSelect('*')
                           ->addAttributeToFilter('state', ['in' => 'new'])
                           ->addAttributeToFilter('created_at', ['gteq'=>$start_date])
                           ;


                $this->_logger->info($orders->getSelect());

                foreach($orders as $_order)
                 $this->_logger->info($_order->getId());


        }
}

2 Answers 2

0

Is the lack of braces around your loop body intentional?

Eg it should be...

foreach($orders as $_order) {
    $this->_logger->info($_order->getId());
}

And just to be "that guy", you should be doing this with repositories and search criteria rather than working directly with a collection.

1
  • I have to add braces since more lines are coming in side foreach.. but for now, just removed it to print something and to check foreach is working. I didn't understand about the repositories?
    – jpk
    Mar 24, 2021 at 3:19
0

Use following code instead of yours:

foreach($orders as $order){
    $this->_logger->info($_order->getData());
}

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.