1

I get best seller product for all category using below code

public function __construct(\Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory

) {
    $this->_collectionFactory = $collectionFactory;

 }


public function getBestSellerData()
{
    $collection = $this->_collectionFactory->create()->setModel(
        'Magento\Catalog\Model\Product'
    );

    return $collection;
}  

How can i add category filter for collection. in magento 1 we can do like that

$catNum = 7; //The number of the category you want to load
$category = Mage::getModel('catalog/category')->load($catNum);
$products = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId)
->addCategoryFilter($category);
2
  • What do you mean exactly? Do you want to filter the collection in your code based on a category id for instance? Or are you talking about frontend layered navigation filters? Please elaborate.
    – Akif
    Commented Feb 17, 2016 at 16:25
  • i need filter collection based on category id.for ex stackoverflow.com/questions/1971429/…
    – Pratik
    Commented Feb 18, 2016 at 5:09

2 Answers 2

1

The only product information returned from the reports bestseller collection is as follows:

[period] => 2018-01-01
[qty_ordered] => 1.0000
[product_id] => 20
[product_name] => product name
[product_price] => 5.7500

hence you will need to do a join and then filter like so

You could also do a join and filter by category

$collection = $this->_collectionFactory->create()->setModel(
            'Magento\Catalog\Model\Product'
        )->join(['secondTable' => 'catalog_category_product'], 'sales_bestsellers_aggregated_yearly.product_id = secondTable.product_id', ['category_id' => 'secondTable.category_id'])
        ->addFieldToFilter('category_id', ['eq' => 43]);

Which will give you below:

[period] => 2018-01-01
[qty_ordered] => 1.0000
[product_id] => 20
[product_name] => Clipbook Classic Pastels Personal Notebook Orchid
[product_price] => 5.7500
[category_id] => 43

So you can addFieldToFilter() based on category_id.

0

I assume that the bestseller collection is the same as normal product collection. You can use:

addCategoriesFilter(array $categoriesFilter)

See also https://magento.stackexchange.com/a/100993/5827

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.