Why Can't I Load a Product by SKU using loadBySku()?

// This method does not work (Of all, I expect this to work)
$product = Mage::getModel('catalog/product')->loadBySku($sku);

This is because the method Mage_Catalog_Model_Product::loadBySku does not exist. There must be a method called loadBySku in the class Mage_Catalog_Model_Product for you to be able to use it, unless it's some magic method.

// These do not work either
$product->getModel('catalog/product')->loadByAttribute($sku, 'sku');
$product->getModel('catalog/product')->loadByAttribute('sku', $sku);

The above includes typos. It should be like below. You need to assign what Mage::getModel()->load() returns to $product before doing stuff with the product object.

$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);

Note that with loadByAttribute, you do not get related objects like the stock and media gallery. See Mage_Catalog_Model_Abstract::loadByAttribute for more info.


I tested execution time for the various methods I've seen to load a product by SKU. This is the most efficient:

$product = Mage::getModel('catalog/product');
$product->load($product->getIdBySku($data['sku']));

Tests:

$time_start = microtime();
$product1 = Mage::getModel('catalog/product')->loadByAttribute('sku', $data['sku']);
$time_end = microtime();
$time1 = $time_end - $time_start;

$time_start = microtime();
$product2 = Mage::getSingleton('catalog/product')->getCollection()
            ->addAttributeToFilter('sku', $data['sku'])
            ->addAttributeToSelect('*')
            ->getFirstItem();
        // do a full product load, otherwise you might get some errors related to stock item
        $product2->load($product2->getId());
$time_end = microtime();
$time2 = $time_end - $time_start;

$time_start = microtime();
$product3 = Mage::getModel('catalog/product');
$product3->load($product3->getIdBySku($data['sku']));
$time_end = microtime();
$time3 = $time_end - $time_start;

echo "<pre>time1: $time1\ntime2: $time2\ntime3: $time3</pre>";

Test results (in seconds):

time1: 0.024642
time2: 0.079715
time3: 0.007891

To load product by SKU in magento you can use the following code:

$_sku = 'leathershoes';
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_sku);
print $_product->getName(); // display product name

I used this everytime and it works perfectly. If you want to load multiple products, try this

$productSku = array('234', '267', '4523', 'Leather shoes', 'skin care'); // insert product SKU here
$attributes = Mage::getSingleton('catalog/config')->getProductAttributes();
$collection = Mage::getModel('catalog/product')
                ->getCollection()                
                ->addAttributeToFilter('sku', array('in' => $productSku))
                ->addAttributeToSelect($attributes);

Reference source http://magentoexplorer.com/how-load-product-by-sku-or-id-in-magento