Magento – Add Category filter in best seller product Collection

best-sellercategorymagento2

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);

Best Answer

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.