Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento collection not selecting attribute

Tags:

magento

Yesterday I wrote some code to pull a collection of products. This code worked fine, however today, the code doe snot work, nothing has changed, I cannot understand why it won't work.

This is what I coded

$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('MPN')
->addAttributeToSelect('JAN')
->addAttributeToSelect('UPC')
->addFieldToFilter(array(
    array('attribute'=>'type_id','eq'=>'simple')
))
->setPage(1,10);
$collection->load();
foreach($collection as $item)
{

echo print_r($item->getdata());
}

Yesterday I was able to see a list of products that contained my MPN's, JAN's and UPC's (these are custom attributes in the backend). Today they don't load at all. It's weird as hell, I think maybe my understanding of collections is not as good as I thought.

Any help would be much appreciated.


EDIT:

Refreshing the magento cache seemed to make everything work again. Does this mean that collection sometimes use the cache, is there some way I can write the code so that it does not use the cache?

like image 266
Lucas Scholten Avatar asked Aug 03 '12 14:08

Lucas Scholten


Video Answer


1 Answers

It depends where are you using your collection. If collection is used on the frontend and the Flat mode is turned on, then your attributes won't be available, since they are not included into Flat index.

To include them into flat index you need to add the following XML configuration into your config.xml file of the module

<config>
    <frontend>
         <product>
              <collection>
                   <attributes>
                      <MPN />
                      <JAN />
                      <UPC />
                   </attributes>
              </collection>
          </product>
    </frontend>
</config>

In this case it will be available in the flat mode. Also by adding attributes into this XML node, your attributes also will be automatically added to all product list collections on the frontend.

Have fun with Magento Development!

like image 112
Ivan Chepurnyi Avatar answered Sep 27 '22 23:09

Ivan Chepurnyi