How to sort product collection by sales in Magento 2
-
12-12-2020 - |
質問
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!
解決
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');
他のヒント
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.
所属していません magento.stackexchange