0

I would like to build a custom module, for Magento 2, that will displays a list of products, from the logged in customer's, order history, and sort it by the best selling products. (e.g. most occurrences in the orders history of that customer)

  • You can try to use this code to get your result : Best selling product – Shashank Gupta Feb 1 '18 at 8:34
  • You can try to use this code to get your result : Best selling product – Shashank Gupta Feb 1 '18 at 8:35
  • 1
    Thanks Shashank, but what I'm looking for is a way to get a collection of all orders and extract the products (with quantities) from all of 'em and calculate the most occurrences from the list – Shay Zalman Feb 1 '18 at 16:15
1

I think you can modify Best selling product

this according to your need -:

  1. collect the collection, group by orderid .
  2. setorder descending then you easily make uniques product array and setPageSize() depend on your need .
0

Found it out.

Here is my working code:

    class MostBought extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Customer\Model\Session $customerSession,
        array $data = []
    ){
        parent::__construct($context);
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->customerSession = $customerSession;
    }
    /**
     * @return string
     */
    public function getMostBoughtProducts()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerId = $this->customerSession->getCustomer()->getId();

        $customerOrders = $objectManager->get('Magento\Sales\Model\Order')->getCollection()
            ->addAttributeToFilter('customer_id', $customerId);

        $products = array();
        foreach($customerOrders as $order){
            foreach($order->getAllItems() as $product){
                if (array_key_exists($product->getSku(), $products)){
                    $products[$product->getSku()] += (int)$product->getQtyOrdered();
                }else{
                    $products[$product->getSku()] = (int)$product->getQtyOrdered();
                }
            }
        }
        arsort($products);
        $skuList = implode(",", array_slice(array_keys($products), 0, 4));
        return $skuList;
    }
}

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.