Magento – Calling Load with Attribute Name

productproduct-attribute

Looking through one of the projects I've been working on, I keep coming across code that does $product->load('attribute_name'), where product is an instance of Mage_Catalog_Model_Product. Digging down through the code for a product model, I fail to see what this is supposed to do. Is this just a misunderstanding by whoever wrote this custom code, or am I missing something?

As far as I'm concerned this would attempt to load a product with the id of 'attribute_code', which doesn't exist. In this situation it would hit Mage_Eav_Model_Entity_Abstract::load with $product, 'attribute_code', array() as the arguments. This would actually mark the current model as new with isObjectNew(true) since it can't be loaded from the database, but since $attributes is empty it will trigger Mage_Eav_Model_Entity_Abstract::loadAllAttributes, which due to the fact the model was partly loaded and thus contains an entity_id already, fetches all attributes from the database for that entity_id. If this is the case, the string 'attribute_code' is somewhat irrelevant (so long as it isn't the entity_id of another product) and all attributes will be loaded for the entity_id contained in the model.

Is my understanding correct, or am I missing something?

Best Answer

In short, yes what you are suggesting is correct. The select statement built when calling the load in you question would be the following.

SELECT `catalog_product_entity`.* FROM `catalog_product_entity` WHERE (entity_id ='attribute_name')

You can find this out by adding some debug into the load method in Mage_Eav_Model_Entity_Abstract

If you are actually wanting to load a product via an attribute that is not entity_id the the following snippet would do it.

Mage::getModel('catalog/product')->loadByAttribute('sku', 'My Sku Value');

NOTE: with loadByAttribute if the attribute is not unique then the first object found will be returned

SECOND NOTE: this will return either an object or false (thanks Fabian)

Related Topic