Magento – How to get a configurable parent product from catalog in Magento2

configurable-productmagento2model

In Magento 1 I had an extension that did the following to get the configurable parent product by child ID:

// $full_product holds the child in the first place
$configurable_product_model = Mage::getModel('catalog/product_type_configurable');
$parentIds= $configurable_product_model->getParentIdsByChild($full_product->getId());
if (count($parentIds) > 0) {
    $full_product = Mage::getModel('catalog/product')->load($parentIds[0]);
}

How can I do the same in Magento2?

Best Answer

In the magento 2 , you need to follow the below steps to get the class methods and to inject its object to our class rather that pulling the object this is what we called the Dependency Injection.

Step 1:

Define the class that your are going to get the object with the keyword

  //here we import the product class 
  use Magento\Catalog\Model\Product;

 //here we import the configurable class
 use Magento\ConfigurableProduct\Model\Product\Type\Configurable;

Step 2:

you need to initialize the configurable product class in your class

  protected $_product;

  protected $_configurable;


 public function __construct(Product $product Configurable $configurable) 
 { 
     //here you would get the product class object
     $this->_product=$product;

     //here you would get the configurable class object
     $this->_configurable=$configurable
  }

Step 3:

If you need to get the associated simple products from the configurable you can try the below code

//the below is used get the configurable product object using configurable product id

$product=$this->_product->load($configurableProductId); 

//the below is used to get the associated simple products using the configurable product object 

$associated_products = $this->_configurable->getUsedProductCollection($product)->addAttributeToSelect('*')->addFilterByRequiredOptions();