0

I've simple product assign in bundle items of Bundle product.

Now I've simple product ID and I'm trying to find in which bundle product it's given in bundle items using following code but it returns an empty array.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$parent = $objectManager->create('Magento\Bundle\Model\Product\Type')->getParentIdsByChild($product->getId());
var_dump($parent);
0

I've done in following way

public function getParentsId(){
        $products =  $this->_productCollection->create();
        $productcollection =$products->addAttributeToFilter([
                                ['attribute'=>'event_start_date','gt'=> date("Y/m/d") ]
                            ]);
        $parents = array();
        foreach ($productcollection as $product) {
            $parent = $this->findBundledProductsWithThisChildProduct($product->getId());
            array_push($parents, $parent);
        }
        return array_unique(array_reduce($parents, 'array_merge', array()));
    }


//Function by Alan Strom
function findBundledProductsWithThisChildProduct($id_to_find)
    {
        //grab all bundled products
        $bundles = array();
        $products = $this->_productCollection->create();
        $products = $products->addFieldToFilter('type_id','bundle');
        //loop over bundled products
        foreach($products as $product)
        {
            //get child product IDs
            $children_ids_by_option = $product
            ->getTypeInstance(true)
            ->getChildrenIds($product->getId(),false); //second boolean "true" will return only
                                                       //required child products instead of all
            //flatten arrays (which are grouped by option)
            $ids = array();
            foreach($children_ids_by_option as $array)
            {
                $ids = array_merge($ids, $array);
            }

            //perform test and add to return value
            if(in_array($id_to_find, $ids))
            {
              $bundles[] = $product->getId();
            }
        }
        return $bundles;
    }
|improve this answer|||||

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.