3

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.

6

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


    }
1
  • 1
    Ty, it has been more difficult bc the product is configurable, but just inserting an array of ids in ->addFieldToFilter('product_id', $ids) works Nov 30 '16 at 15:23

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.