开发者

How to get parent product id in magento?

开发者 https://www.devze.com 2023-03-27 17:42 出处:网络
I know that in Magento 1.4.2.0 one gets parent id\'s like so list( $parentId ) = Mage::getModel(\'catalog/product_type_configurable\')

I know that in Magento 1.4.2.0 one gets parent id's like so

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

My question is: if I don't know what the parent is, how do I know to use the 'catalo开发者_StackOverflowg/product_type_configurable' vs 'catalog/product_type_grouped' model to get the id?


You can just call both and offer a fall-back as it should be one or the other:

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


You may use:

$product->getTypeInstance();

Which will return the type object of your product

Then you can perform your:

->getParentIdsByChild()

Giving finally:

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


Here is another solution for magento 1.7.2

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


we can use in block file,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;     
        }   


You could check the type of the product with $_product->getTypeId(); and if this returns 'configurable', take the configurable model and if it returns 'grouped' take the grouped model.

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号