New developers often ask me how to load a product by a particular attribute. This is quite easy to accomplish in Magento and can be done using Magento collections.
Load a Product by SKU
Unlike most product attributes, SKU is a static attribute. This means that instead of being stored in one of the products EAV tables, it is stored in the main product entity table (catalog_product_entity). This makes loading a product based on it’s SKU much easier and efficient.
|
1
2
3
4
5
6
7
8
9
10
11
|
<?php $sku = 'my-product-sku'; $product = Mage::getModel('catalog/product')->load($sku, 'sku'); if ($product->getId()) { echo $product->getName(); } else { echo 'Product not found with SKU of ' . $sku; } |
The above code makes use of the load method, which is available for all EAV entities in Magento. By default this method takes two parameters: a value that’s used to match the product and the field that the values is checked against. If the second parameter is empty, Magento will use the primary key, which is usually the model ID. By passing a static attribute (SKU is the only useful static attribute for this context), it is possible to load a product model on a different value.

