可配置产品-获取子产品ID


Answers:


4

请尝试以下解决方案:

<?php
    $productId = 5; //Configurable product ID
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $_objectManager->create('Magento\Catalog\Model\Product')->load($productId);
    $_childProducts = $_product->getTypeInstance()->getUsedProducts($_product);
    foreach ($_childProducts as $simpleProduct){
        echo $simpleProduct->getId();
    }
?>

建议:不要在代码中直接使用对象管理器,因为这不是最佳实践。您需要将产品模型类注入到您各自的类中,然后使用它。


是的,我已经注入模型并且工作正常。感谢@sukumar
Sanjay Vadadoriya

欢迎。快乐编码:)
Sukumar Gorai

2

尝试使用此代码:

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

$_children = $configProduct->getTypeInstance()->getUsedProducts($configProduct);

foreach ($_children as $child){
    echo $child->getID();
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.