0

I want to get the products ordered within a date range for a report.

As the result, I need like, product, product type, product Qty.

I tried to load all orders and get the sum of products, it want working out.

$orders = $this->orderCollectionFactory->create()
        ->addAttributeToFilter('created_at', array('from'=>$dateFrom, 'to'=>$dateTo))
        ->addFieldToFilter('status', array('nin' => array('canceled','refund_request','refunded', 'return_exchange_request')));

How can I get the products count individually for each product from this collection?

Expecting result |Product-+-type---+-Qty-| +--------+--------+-----+ | P1 | simple | 10 |

1 Answer 1

0
protected $itemFactory;
protected $orderFactory:

public function __construct(
  \Magento\Sales\Model\Order\ItemFactory $itemFactory,
  \Magento\Sales\Model\OrderFactory $OrderFactory

) {
   $this->itemFactory = $itemFactory;
   $this->orderFactory = $OrderFactory;

}

then in your function

$order = $this->orderFactory->create()->getCollection()
->addFieldToFilter('status', array('nin' => array('canceled','refund_request','refunded', 'return_exchange_request')))
->addFieldToFilter('created_at', ['gteq' => $dateFrom])
->addFieldToFilter('created_at', ['lteq' => $dateTo]);
foreach($order->getAllVisibleItems() as $Items){
  $orderId = $Items->geId();
  $orderItems = $this->itemFactory->create()->getCollection()
  ->addFieldToFilter('order_id', $orderId);
  foreach($orderItems as $item){
    $qty = $item->getQtyOrdered();
    $type = $item->getProductType();
    $productId = $item->getProductId();
    //etc
  }
}

the data is fetched from sales_order_item table.

2
  • i am getting an error here ->addFieldToFilter('status', array('nin' => array('canceled','refund_request','refunded', 'return_exchange_request')))
    – Mujahidh
    Jul 5, 2021 at 11:51
  • Please check the edited answer!
    – Mehran
    Jul 5, 2021 at 12:52

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.