I am trying to get all products of specific category whether these products are directly listed in the category or in the subcategories under this specific category I really searched for this on google and Magento Stack Exchange and found nothing about Magento 2, all I found are some topics on Magento 1,
Here is What I just reached,
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
class ChildProducts extends Action
{
protected $resultJsonFactory;
protected $_categoryFactory;
protected $productCollectionFactory;
public function __construct(Context $context, JsonFactory $jsonFactory ,\Magento\Catalog\Model\CategoryFactory $categoryFactory ,
CollectionFactory $productCollection)
{
$this->_categoryFactory = $categoryFactory;
$this->resultJsonFactory = $jsonFactory;
$this->productCollectionFactory = $productCollection;
parent::__construct($context);
}
public function execute()
{
// get parent category
$categoryId = $this->getRequest()->getParam('category_id');
$productCollection = $this->productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');
$productCollection->addCategoriesFilter(array('in' => $categoryId));
return $this->resultJsonFactory->create()->setData($productCollection);
}