How to display “customer based” best sellers list?
-
29-12-2020 - |
سؤال
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)
المحلول 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;
}
}
نصائح أخرى
I think you can modify Best selling product
this according to your need -:
- collect the collection, group by orderid .
- setorder descending then you easily make uniques product array and setPageSize() depend on your need .
لا تنتمي إلى magento.stackexchange