Showing posts with label Clone. Show all posts
Showing posts with label Clone. Show all posts

Thursday 14 June 2018

Forloop query not workin in Magento 2 | Get same Ordered Qty of all products in Magento 2

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$soldModel = $objectManager->get('Magento\Reports\Model\ResourceModel\Product\Sold\Collection');
$collections = $productCollection->addAttributeToSelect('*')->setOrder('entity_id', 'desc')->load();
$productdata = array();
foreach ($collections as $product){
         
            $soldproduct = clone $soldModel;
            $soldproduct = $soldproduct->addOrderedQty()->addAttributeToFilter('product_id', $product->getId())->setOrder('ordered_qty', 'desc')->getFirstItem();
            $sold = (int)$soldproduct->getOrderedQty();
         
            $product->setSold($sold);
            $productdata['products'][] = $product->getData();
}
echo '<pre>';print_r($productdata);