mystix
3/30/2013 - 5:01 PM

magento - grab all simple products having prices different from their parent configurable product, then update them to match

magento - grab all simple products having prices different from their parent configurable product, then update them to match

<?php

$store_id = 0;
$action = "view";

// bootstrap magento (default store)
require_once('app/Mage.php'); // path to magento
umask(0);
Mage::app()->setCurrentStore($store_id); // TODO - 3

echo 'loading store id: ' . $store_id . '<br />';

// set script timeout to 20 minutes
set_time_limit(1200);

// grab ALL configurable products in the store
$configurables = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToFilter('type_id', 'configurable')
        ->addAttributeToSelect('sku')
        ->addAttributeToSelect('price'); // because the "price" attribute isn't automatically loaded in the product collection

// store all simple products with prices different from the parent product
$mismatch = array();


foreach($configurables as $configurable) {
    // grab ALL simple product ids associated with the current configurable product
    foreach($configurable->getTypeInstance()->getUsedProductIds() as $id) {
        $simple = Mage::getModel('catalog/product')->load($id);

        if ($simple->getPrice() != $configurable->getPrice()) {
            if ($action == "view") {        
                $cfgSku = $configurable->getSku();
            
                if (!isset($mismatch[$cfgSku])) {
                    $mismatch[$cfgSku] = array(
                        'price'         => $configurable->getPrice(),
                        'associated'    => array()
                    );
                }
            
                $mismatch[$cfgSku]['associated'][] = array(
                    'sku'   => $simple->getSku(),
                    'price' => $simple->getPrice()
                );
            } else {
                // update simple product's price to match parent configurable's price
                $simple->setPrice($configurable->getPrice())->save();
            }
        }
    }
}

print_r($mismatch);