Retrieving Grouped Product IDs from Purchases and Cart
Grouped products are a powerful way to manage promotions and special offers in Magento 2. However, tracking these grouped products can be complex due to their hierarchical nature. In this post, we’ll guide you through retrieving the grouped product ID from both purchases (orders) and cart/quote.
Retrieving Grouped Product IDs from Orders
When a simple product is purchased as part of a grouped product, Magento stores relevant data in various arrays within the order object. Here’s how to extract the required information:
$order = $block->getOrder();
$groupedProductIds = [];
foreach ($order->getAllItems() as $item) {
if($item->getParentItemId()) {
// Check if the item is a child of a grouped product
$groupedProductIds[] = $item->getSuperProductConfig()->getGroupedParentId();
}
}
print_r($groupedProductIds); // Outputs: Array ([0] => 123, [1] => 456)
In this code snippet, we loop through all items in the order. We check if the item is a child of a grouped product using its getParentItemId() method. If it is, we use the getSuperProductConfig() and getGroupedParentId() methods to retrieve the ID of the parent (grouped) product.
Retrieving Grouped Product IDs from Cart/Quote
To retrieve grouped product IDs from a cart or quote, you can use the following approach:
$quoteId = $block->getQuote()->getId();
$quoteItemCollection = $this->_quoteFactory->create()->load($quoteId)->getAllItems();
foreach ($quoteItemCollection as $item) {
if($item->getParentItemId()) {
// Check if the item is a child of a grouped product
$groupedProductIds[] = $item->getSuperProductConfig()->getGroupedParentId();
}
}
Here, we first retrieve the quote ID using the current block’s quote. We then create a new quote object and load it with the retrieved ID to access all items in the cart. The rest of the process is similar to retrieving grouped product IDs from orders.
Conclusion
Retrieving grouped product IDs from purchases and cart/quote requires navigating through the hierarchical data structure of Magento 2. By using the appropriate getter methods for parent item IDs, super product configurations, and grouped parent IDs, you can effectively track which simple products are part of which grouped promotions.
Remember to use these methods in the context of your specific business logic, such as tracking promotion usage or applying special pricing rules.
For more advanced techniques on managing grouped products and promotions, consider exploring our comprehensive guide on Laravel Company’s Magento 2 Promotion Management Strategies.