Fix Flat Catalog Product Option ‘Yes/No’ Issue in Magento

eavflat-catalogproduct-attributeproduct-collection

I am getting all brands in my magento.When Flat catalog product is set to No, it fine. When it is no i got different result than i expected.

My Code

$attribute_code = array('apparelbrand','bagbrand','beltbrand','jewelrybrand','shoebrand','watchbrand');
foreach($attribute_code as $attribute_code)
    {
        $options= Mage::getSingleton("eav/config")->getAttribute("catalog_product", $attribute_code)->getSource()->getAllOptions(false); 
        foreach($options as $option)
        {   
            $collection = Mage::getModel('catalog/product')->getCollection();
            $collection->addAttributeToFilter($attribute_code, $option["value"])->addAttributeToFilter('status', array('eq'=>1));
            if(count($collection->getAllIds())>0)//Checks whether the product exist for particular brand
            {   
                Mage::log($option["label"].":".count($collection->getAllIds()));
                $cat[strtoupper(substr($option["label"],0,1))][]=$option["label"];//creates the multi-dimensional array of brand value with the starting character as key
            }
        }
    }

The above code results as

Flat Catalog Product = No

brand1 : 2
brand2 : 5
brand6 : 5
.
.
etc..

Flat Catalog Product = Yes

brand1 : 2
brand2 : 5
brand3 : 128
brand4 : 128
brand5 : 128
brand6 : 5
.
.
etc..

Why the count() returns 128 instead count even the brand does not have that much products.What could be the reason for this problem?

Best Answer

There is core Magento "feature" which makes non-flat attributes not working in addAttributeToFilter() filtering when you use simple form:

addAttributeToFilter($attribute, $value)

Try to change this to following form:

addAttributeToFilter(array(array('attribute' => $attribute_code, 'eq' => $option["value"])))

Another thing which is not exactly related with your question, is that you could try to optimize your code - eg. change count($collection->getAllIds()) calls to $collection->getSize().

Related Topic