3

I need a way to get latest 100 Orders including the ordered sku(s).

This is what I tried:

use Magento\Framework\View\Element\Template;

class Orders extends Template
{
protected $_orderCollectionFactory;

public function __construct(
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,        
        \Magento\Framework\View\Element\Template\Context $context,
        array $data = [])
    {
        $this->_orderCollectionFactory = $orderCollectionFactory;
        parent::__construct($context, $data);
    }
protected function _prepareLayout()
{

    // get last 100 orders
    $ordercollection =$this->_orderCollectionFactory->create()->addFieldToSelect(array('*'));
    $ordercollection->setOrder('entity_id','DESC');
    $ordercollection->setPageSize(100);
    $ordercollection->setCurPage(1);

    $this->setOrdersColl($ordercollection);
}
}

In my template file:

<?php
    $ordercollection1 = $this->getOrdersColl();

    foreach ($ordercollection1->getItems() as $order) {
        echo "<br>order: ".json_encode($order->getData());
    };
?>

Result: The Orders are printed out individuallay as arrays, each containing order informations (as array elements).

BUT I am missing the ordered product sku or id in those order arrays.

I need to know which products were ordered. Any help on how I can get sku of the ordered item ?

Thanks

1 Answer 1

6

If you want to get product SKU inside order, you can try the following code in your template file:

foreach ($ordercollection1->getItems() as $order) {
    echo "<br>order: ".json_encode($order->getData());
    $items = $order->getAllItems();
    foreach($items as $item) {
        echo "SKU: " . addslashes($item->getSku());
        echo "ID: " . addslashes($item->getId());
    }
};

OT: I added addslashes on SKU. It can prevent the SKU contain quote that caused unexpected syntax error.

2

Your Answer

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

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