乐趣区

关于magento2:get-child-item-id-of-configurable-product-by-super-attribute

Let’s assume you know configurable product id and used child product super attribute details.
Example from Magento Sample data configurable product name Chaz Kangeroo Hoodie, Configurable product id is 67.
Super attribute Array details,

[super_attribute] => Array
([93] => 49
    [254] => 167
)

Using the bove details how we can get details of child item.

Refer below code snippet for Get child item id of a Configurable product by child’s Attribute details.

<?php
public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable
) {
    $this->productRepository = $productRepository;
    $this->configurable = $configurable;
}
/* Pass Configurable product id as $configId 
 * Pass array of super attribute of child item
 */
public function getChildFromProductAttribute($configId,$superAttribute) {$_configProduct = $this->productRepository->getById($configId);
    $usedChild = $this->configurable->getProductByAttributes($superAttribute ,$_configProduct);
    $childProductId = $usedChild->getId();
    return $childProductId;
}

Call function,

$configId = 67; //Configurable Product id
$superAttribute = Array(93 => 49,254 => 167); //childs super attribute details
$childId = $this->getChildFromProductAttribute($configId,$superAttribute);

Result is 52(Product name Chaz Kangeroo Hoodie-XS-Black). Using above way we got the child item data.

退出移动版