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

时间:2011-08-10 16:41:45

标签: php magento magento-1.4

我知道在Magento 1.4.2.0中可以得到父ID,就像这样

list( $parentId ) = Mage::getModel('catalog/product_type_configurable')
                            ->getParentIdsByChild( $product->getId() );

我的问题是:如果我不知道父母是什么,我怎么知道使用'catalog / product_type_ 可配置'vs'catalog / product_type_ 分组'获得身份证的模特?

5 个答案:

答案 0 :(得分:33)

你可以同时打电话给两个人并提供一个回落,因为它应该是一个或另一个:

if($product->getTypeId() == "simple"){
    $parentIds = Mage::getModel('catalog/product_type_grouped')->getParentIdsByChild($product->getId());
    if(!$parentIds)
        $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
    if(isset($parentIds[0])){
        $parent = Mage::getModel('catalog/product')->load($parentIds[0]);
        // do stuff here
    }
}

答案 1 :(得分:9)

您可以使用:

$product->getTypeInstance();

将返回产品的类型对象

然后你可以执行你的:

->getParentIdsByChild()

最后给予:

$product->getTypeInstance()->getParentIdsByChild($child->getId());

答案 2 :(得分:7)

这是magento 1.7.2的另一个解决方案

$parentIds = Mage::getSingleton('catalog/product_type_configurable')->getParentIdsByChild($mageProduct->getId());

答案 3 :(得分:1)

我们可以在块文件中使用magento 2,

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

答案 4 :(得分:0)

您可以使用$_product->getTypeId();检查产品的类型,如果返回“可配置”,请使用可配置模型,如果返回“已分组”,请使用分组模型。

希望这有帮助。