Question

I need to sort products on catalog page by ordered quantity.

What is the best way to do it?

I know that table sales_order_item contains this data, but I think direct SQL queries is bad practice (like SELECT SUM(qty_ordered) FROM sales_order_items WHERE product_id = {$product id} and then sort it).

So I want to find good solution.

Thanks!

Was it helpful?

Solution

I've found solution myself:

$collection = $this->_productCollection->create()
    ->joinField(
        'qty_ordered',
        'sales_bestsellers_aggregated_yearly',
        'qty_ordered',
        'product_id=entity_id',
        array('store_id' => $this->_storeManager->getStore()->getId()),
        'left'
    )
    ->addAttributeToSelect('*')
    ->setOrder('qty_ordered');

OTHER TIPS

You need create new attribute for products and save/update number of sales in this attributes. Then you can sort by new attribute using native magento interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top