0

How do I get all simple product not associate with any configurable , bundle , group product in Magento API 2 ?

0

Try this code

    protected $productCollectionFactory;
    protected $configurable;
    protected $grouped;
    protected $bundleSelection;

    public function __construct(
        ...........................................................
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable,
        \Magento\Bundle\Model\Product\Type $bundleSelection,
        \Magento\GroupedProduct\Model\Product\Type\Grouped $grouped,
        ...........................................................

    ) {
        ...........................................................
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->configurable = $configurable;
        $this->grouped = $grouped;
        $this->bundleSelection = $bundleSelection;
        ...........................................................
    }

    public function GetSimpleProductIds($slider_type)
    {
        $allProducts = $this->_productCollectionFactory->create();
        $ChildPrdIds = [];
        $simplePrdIds = [];
        foreach ($allProducts as $product) {
            $parentId = $this->getParentProductId($product->getId());
            if ($parentId) {
                $ChildPrdIds[] = $this->getParentProductId($product->getId());
            } else {
                $simplePrdIds[] = $product->getId();
            }
        }
        $ChildPrdIds = array_unique($ChildPrdIds);
        $simplePrdIds = array_unique($simplePrdIds);

        return $simplePrdIds;
    }

    public function getParentProductId($childId)
    {
        $parent_id = 0;
        // check into conifg product
        $product = $this->configurable->getParentIdsByChild($childId);
        if (isset($product[0])) {
            $parent_id = $product[0];
            return $parent_id;
        }
        // for check into group product
        $groupIds = $this->grouped->getParentIdsByChild($childId);
        if (isset($groupIds[0])) {
            $parent_id = $groupIds[0];
            return $parent_id;
        }
        // for get bundel product pranet id
        $budel_id = $this->bundleSelection->getParentIdsByChild($childId);
        if (isset($budel_id[0])) {
            $parent_id = $budel_id[0];
            return $parent_id;
        }
        return $parent_id;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.