Pregunta

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)

¿Fue útil?

Solución 2

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;
    }
}

Otros consejos

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 .
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top