Magento 2: Get Related products from Product Id now showing Name and price
-
31-01-2021 - |
Question
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>";
}
}
Solution
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>";
}
}
OTHER TIPS
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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange