Magento 2 – How to Get Number of Times a Product Has Been Ordered

magento2ordersproductsales-order

I need the number of orders made by each product.

I have the object

\Magento\Catalog\Model\Product

With that object I can retrieve the Id, price, name, etc. But no idea how to get the number of orders made. Don't see any method to achieve that. There are getQty() that I really don't know what retrieves. it's always null.

I only have the alternative to search the object "sells" or something like that, loop it and retrieve all sells made with that product. but c'mon, I think it has to be an easier way.

Best Answer

You can use following code to get Number of time product ordered

 protected $itemCollection;

  public function __construct(
        .....

        \Magento\Sales\Model\ResourceModel\Order\Item\CollectionFactory $itemCollection,    
         ...
    ) {



        ...
        $this->itemCollection=$itemCollection;
        ....
    }
    public  function getProductOrder()
    {
        $productId=10;  //add you product id here
        $itemCollection = $this->itemCollection->create()
                       ->addFieldToFilter('product_id',$productId);
        echo count($itemCollection); // this will give number of time ordered
        $itemCollection ->getSelect()
                ->columns('SUM(qty_ordered) as total_qty')
                ->group('product_id');

        $itemCollection->getFirstItem()->getTotalQty(); // this will give number of product quantity sold


    }
Related Topic