Magento – get product collection and subcategory id using category id magento 2

magento2

I want to get product collection and subcategory using category id.

I am trying

$category =  2;
    $product = $this->productFactory->create()->getCollection();
    $product->addAttributeToSelect('*');
    $product->addAttributeToFilter('category_ids',$category);

But it gives error like this

Column not found: 1054 Champ 'e.category_ids' inconnu dans where clause,…

And how to get subcategory id from category id?

Best Answer

Please change like this and it will works.

$collection = $this->productFactory->create()
->getCollection()
->addAttributeToSelect('*')
->addCategoriesFilter(['eq' => 2]);
Related Topic