Question

As an example, say I would want to change the filter navigation for categories to add a title attribute to the links generated. The file

/app/design/frontend/base/default/template/catalog/navigation/left.phtml

contains the category object ($_category). However, the attribute meta_title isn't loaded for that object.

Straight forward, I could load a second category object, but that loads a lot of attributes that $_category already contains.

So I'm looking for the most lightweight way to load additional attributes for a given object, and best would be without loading a new object of the same type.

Was it helpful?

Solution

You are right, calling load for each category is a performance killer.
Also loading an attribute for a category separately does not scale, because you will have to do a query for each category.
So you can just add the attribute to the category collection when the collection is loaded.
Here is the stack trace of what happens.

In /template/catalog/navigation/left.phtml this method is called to retrieve the categories. <?php $_categories = $this->getCurrentChildCategories() ?> where $this is an instance of Mage_Catalog_Block_Navigation.
Inside this method at one point $category->getChildrenCategories() is called where $category is the current category object that is an instance of Mage_Catalog_Model_Category.
The method getChildrenCategories is this class is just a wrapper for Mage_Catalog_Model_Resource_Category::getChildrenCategories.
You can rewrite this method and add your attribute in the collection, but this method does the actual loading of the collection, so you better rewrite the method that prepares the collection.
This one is _getChildrenCategoriesBase from the same class.
Make it look like this:

protected function _getChildrenCategoriesBase($category)
{
    $collection = parent::getCollection($category);
    $collection->addAttributeToSelect('meta_title')
    return $collection;
}

Here is a nice explanation on how to rewrite a resource model: https://stackoverflow.com/a/15921599/2047249

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top