How to get parent group Product ID from getParentIdsByChild() method of \Magento\GroupedProduct\Model\Product\Type\Grouped?

magento.stackexchange https://magento.stackexchange.com/questions/267585

  •  24-02-2021
  •  | 
  •  

سؤال

Currently, I am having an issue with retrieving group parent product_id using PHP external script wich file resides under /pub directory:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);
use Magento\Framework\App\Bootstrap;
require '../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productRepository = 
$objectManager->get('\Magento\Catalog\Model\ProductRepository');

$typeGroup = $objectManager->get('\Magento\GroupedProduct\Model\Product\Type\Grouped');

//child product_id
$simple_child_associated_to_group_product_id = 13884;
$product = $productRepository->getById($simple_child_associated_to_group_product_id);

//this returns the 
//row_id of the parent not the product_id
$groupParentIds = $typeGroup->getParentIdsByChild($product->getId());


//shortens the array by one element and store it to a variable
$groupParentId = array_shift($groupParentIds); 

//display group parent id
echo $groupParentId; 

You can confirm the echoed value is the row_id value of getParentIdsByChild() using this query in your M2 Database:

SELECT * FROM `catalog_product_entity` WHERE `row_id` = 'put $groupParentId value here'

Take note of the entity_id:23526

enter image description here To confirm that the returned value of $groupParentId is truly the parent product of the child simple... you can confirm this by:

log-in to your admin panel, go to catalog > products, then search the parent product via ID filter with value of 23526 enter image description here

click the row to open the product info. and check the associated simple products in the Grouped Products section.

هل كانت مفيدة؟

المحلول

@Mhitchauhan answered my question by using this line of codes in my PHP external script file:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager 
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); 
$connection = $resource->getConnection(); 
$tableName = $resource->getTableName('catalog_product_entity'); //gives table name with prefix 
//Select Data from table 
$sql = "Select * FROM " . $tableName ." where row_id='$row_id'"; 
$result = $connection->fetchAll($sql); 
var_dump($result);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى magento.stackexchange
scroll top