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.

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top