Dienstag, 1. April 2014

Magento how to remove duplicated sku

I messed up an import and got duplicated sku's. To fix it I search for duplicated products and remove all but the one with the newest update timestamp:

<?php
// find same sku, order by updated_at
$r2 = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('sku', $product['sku'])
    ->setOrder('updated_at', 'DESC')
    ->load();

// if there is a duplicate
if (count($r2) > 1 )
{
    echo "<br>" . $product['sku'] . ", " . count($r2) . "<br>";
    $i = 0;
    foreach ($r2 as $key => $p)
    {
        if ($i == 0)
        {
            // keep first
            echo $p->getCreatedAt() . ", " . $p->getUpdatedAt() . " keep<br>";
        }
        else
        {
            // remove others
            echo $p->getCreatedAt() . ", " . $p->getUpdatedAt() ." delete<br>";
            $p->delete();
        }
        $i++;
    }
}

Keine Kommentare: