0

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.

0

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

| improve this answer | |
  • thanks got it to work – user3685048 Jul 7 at 20:28
  • Oh good, I was in a hurry and I only use its opposite to get parent from children so didn't have time to put code in. – iphigenie Jul 9 at 7:50
  • I updated the post. This is about 10 times faster. – user3685048 Aug 4 at 2:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.