Is there any way I can fetch all the variants of a configurable products from a product collection in Magento 2? Thanks!
I would like to return the products including the attribute options and and child products as well. So far, I have the code from \Magento\Catalog\Model\ProductRepository::getList()
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
{
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $this->collectionFactory->create();
$this->extensionAttributesJoinProcessor->process($collection);
foreach ($this->metadataService->getList($this->searchCriteriaBuilder->create())->getItems() as $metadata) {
$collection->addAttributeToSelect($metadata->getAttributeCode());
}
$collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
$collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
//Add filters from root filter group to the collection
foreach ($searchCriteria->getFilterGroups() as $group) {
$this->addFilterGroupToCollection($group, $collection);
}
/** @var SortOrder $sortOrder */
foreach ((array)$searchCriteria->getSortOrders() as $sortOrder) {
$field = $sortOrder->getField();
$collection->addOrder(
$field,
($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
);
}
$collection->setCurPage($searchCriteria->getCurrentPage());
$collection->setPageSize($searchCriteria->getPageSize());
$collection->load();
$searchResult = $this->searchResultsFactory->create();
$searchResult->setSearchCriteria($searchCriteria);
$searchResult->setItems($collection->getItems());
$searchResult->setTotalCount($collection->getSize());
return $searchResult;
}
However, this collection does not retrieve the attribute options from configurable products.
Best Answer
You can do it like this
You may be interested in some below functions
For More you can refer the model class
https://github.com/magento/magento2/blob/ffea3cd/app/code/Magento/ConfigurableProduct/Model/Product/Type/Configurable.php