Counting Child Items Without Using Associated Products function
-
13-04-2021 - |
Question
I am counting associated products to show the the number of child items on grouped product in the category page. This is however very resource intensive. Is there a better way to show the count of the number of child products?
<?php
$_productCollection = $block->getLoadedProductCollection();
foreach ($_productCollection as $_product):
$associatedProductsCount = count($_product->getTypeInstance()->getAssociatedProducts($_product));
?>
<?php if($associatedProductsCount):?>
<p><?php echo sprintf('%s Items Available', $associatedProductsCount)?></p>
<?php endif;?>
<?php endforeach; ?>
Edit I want to note that I went and tried the accepted answer in a small production environment v2.3.3 and it was about 10 times faster(I.E .0103 vs .00189 seconds) per call.
Solution
Look at the links I think that's one step behind the associated product collection and doesnt load the products
Magento\Catalog\Model\ResourceModel\Product\Link
function getChildrenIds($parentId, $typeId)
and I think the typeId for related is 3, but check.
Note that this does not do checks for available on site, enabled/disabled etc which is part of its speed