4

Below is my code to get related products from products id, It is working fine but not giving values for name and price it just gives SKU and id

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($lastid);

    $relatedProducts = $product->getRelatedProducts();

    if (!empty($relatedProducts)) {
        echo 'Related Products <br />';   
        foreach ($relatedProducts as $relatedProduct) {
            echo $relatedProduct->getId().'-->'.$relatedProduct->getPrice().'-->'.$relatedProduct->getName().'-->'.$relatedProduct->getId(); //get name
            echo "<br>";
        }
    } 
5
  • what you are getting when var_dump($relatedProducts); ?
    – Pawan
    Commented Oct 14, 2018 at 5:09
  • where do you want to show this related products ?
    – Pawan
    Commented Oct 14, 2018 at 5:48
  • on checkout success.phtml Commented Oct 14, 2018 at 5:51
  • Please see my answer
    – Pawan
    Commented Oct 14, 2018 at 5:59
  • did you try my solution ?
    – Pawan
    Commented Oct 14, 2018 at 12:39

2 Answers 2

1

There can be a better solution, But for now you need to load product in loop, Which will give you all the data of product.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($lastid);

$relatedProducts = $product->getRelatedProducts();

//var_dump($relatedProducts);

if (!empty($relatedProducts)) {
    echo 'Related Products <br />';   
    foreach ($relatedProducts as $relatedProduct) {
        $_product = $objectManager->create('Magento\Catalog\Model\Product')->load($relatedProduct->getId());
        echo $relatedProduct->getId().'-->'.$_product->getPrice().'-->'.$_product->getName().'-->'.$relatedProduct->getId(); //get name
        echo "<br>";
    }
}  
1
  • This was really slow in my case (I have lots of related products). Karpa's solution is much faster, you just have to specify each field you want loaded.
    – Art Siv
    Commented Dec 14, 2021 at 18:58
2

You can (should) avoid load each product in the loop. You can add the desired attributes in the collection and then use them in your loop.

$relatedProducts = $_product->getRelatedProductCollection()
                            ->addAttributeToSelect('color', 'name');

foreach ($relatedProducts as $relatedProduct) {
    // echo $relatedProduct->getSku();  
    echo $relatedProduct->getName(); //get name
    echo $relatedProduct->getData('color'); //or getColor()
    // echo print_r($relatedProduct->getData(), true); //Show all attributes      
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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