如何在magento 2中获取父产品ID?


Answers:


26

要在phtml文件中获取父产品ID,您可以通过以下方式直接调用代码:

    $productId = 52; //this is child product id
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->create('Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable')->getParentIdsByChild($productId);
     if(isset($product[0])){
         //this is parent product id..
         echo $product[0];
    }

在查看文件中正常工作。

7
您不应该使用对象管理器目录。使用-> create方法注入工厂
CarComp

@Rakesh在获取可配置产品ID之后,如何才能仅获取有关特定可配置产品的所有详细信息?我可以通过上级产品ID加载产品型号吗?
Sanjay Gohil

12

您可以通过Magento的特定方式将其称为块文件,

protected $_catalogProductTypeConfigurable;

public function __construct(
    \Magento\Catalog\Block\Product\Context $context,
    //for getting parent id of simple
    \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $catalogProductTypeConfigurable,
    array $data = []
) {
    //for getting parent id of simple
    $this->_catalogProductTypeConfigurable = $catalogProductTypeConfigurable;
    parent::__construct($context, $data);
}

public function getProductData($id) {
    $parentByChild = $this->_catalogProductTypeConfigurable->getParentIdsByChild($id);
    if (isset($parentByChild[0])) {
        //set id as parent product id...
        $id = $parentByChild[0];
    }
    return $id;
}

未指定家长班!我认为其Magento\Catalog\Block\Product\AbstractProduct???
Imran Zahoor,2016年
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.