0

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!

2

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');
| improve this answer | |
0

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.

| improve this answer | |
  • Do you mean create _afterSave to order model and increment this attribute? – Kyrylo Romantsov Sep 15 '17 at 10:21
  • Yes. Or create plugin <type name="Magento\Sales\Api\Data\OrderInterface"> <plugin name="eventSalesOrderStatus" type="....."/> </type> – Alex Sep 15 '17 at 10:59
  • My techlead says it is bad practice – Kyrylo Romantsov Sep 15 '17 at 21:22
  • What is good practice? – Alex Sep 18 '17 at 10:19
  • I've just posted topic about this ) magento.stackexchange.com/questions/194058/… – Kyrylo Romantsov Sep 21 '17 at 8:27

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.