1

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>";
        }
    } 
  • what you are getting when var_dump($relatedProducts); ? – Pawan Oct 14 '18 at 5:09
  • where do you want to show this related products ? – Pawan Oct 14 '18 at 5:48
  • on checkout success.phtml – user1799722 Oct 14 '18 at 5:51
  • Please see my answer – Pawan Oct 14 '18 at 5:59
  • did you try my solution ? – Pawan Oct 14 '18 at 12:39
0

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>";
    }
}  
0

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, privacy policy and cookie policy

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