I have some experience in M1 and M2 but am somewhat struggling to grasp how to load the child category. At the minute it loads the default M2 category with [0] or [1] next category etc. But I just want to load the last category the product is attached too. Imagine Default > Electrics > Stereo > Cables. I just want to load the cables version, I know I could do it by doing [3] but imagine if another category only had Default > Electrics > Stereo it would then be [2] and I need that logic to be dynamic.
Pease can someone help, I've been crawling for hours and getting more and more confused.
This code relates to a custom related products module which is built to simply load products in the same last category view.
class Related extends Template { protected $_productCollectionFactory; protected $_categoryFactory; protected $_registry;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Catalog\Model\CategoryRepository $categoryRepository
)
{
$this->_categoryFactory = $categoryFactory;
$this->_productCollectionFactory = $productCollectionFactory;
$this->_registry = $registry;
$this->categoryRepository = $categoryRepository;
parent::__construct($context);
}
public function getRelatedProducts()
{
$categoryIds = $this->_registry->registry('current_product')->getCategoryIds();
$category = $this->_categoryFactory->create()->load($categoryIds[0]);
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*')
->addCategoryFilter($category)
->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setPageSize(5);
return $collection;
}
}