How to get sku's of selected bundle products from order item?
-
16-10-2019 - |
Question
I see only product titles of products that are selected in product_options property of order item. Is there any way to get ids or skus of those products?
Solution
Instead of using $order->getAllItems()
use the sales item collection itself:
$collection = Mage::getResourceModel('sales/order_item_collection')->addFieldToFilter('order_id',array('eq'=>$order_id));
Where $order_id
is the entity_id of the sales_order.
To use this collection, iterate over it - all items are available, even children items of bundles and configurables -- e.g. not just visible items:
foreach($collection as $_item){
var_dump($_item->getSku());
}
OTHER TIPS
Actually, there is a way to get the option skus from the order item - and without having to load any products. Observe!
foreach($order->getAllItems() as $item) {
$options = $item->getProductOptions();
$optionIds = array_keys($options['info_buyRequest']['bundle_option']);
$types = Mage_Catalog_Model_Product_Type::getTypes();
$typemodel = Mage::getSingleton($types[Mage_Catalog_Model_Product_Type::TYPE_BUNDLE]['model']);
$typemodel->setConfig($types[Mage_Catalog_Model_Product_Type::TYPE_BUNDLE]);
$selections = $typemodel->getSelectionsCollection($optionIds, $item);
$selection_map = array();
foreach($selections->getData() as $selection) {
if(!isset($selection_map[$selection['option_id']])) {
$selection_map[$selection['option_id']] = array();
}
$selection_map[$selection['option_id']][$selection['selection_id']] = $selection;
}
$chosen_skus = array();
foreach($options['info_buyRequest']['bundle_option'] as $op => $sel) {
$chosen_skus[] = $selection_map[$op][$sel]['sku'];
}
echo "Item ".Mage::getResourceModel('catalog/product')->
getAttributeRawValue($item->getProductId(), 'sku', $item->getStoreId()).
" has chosen SKUs: ".implode(', ', $chosen_skus)."\n";
}
The items are stored in the sales_flat_order_item table as seperate rows (items), the items have the parent_item_id field set to the ID of the bundle product row.