Magento – addAttributeToFilter with dropdown values

collection;

Given a dropdown attribute such as color:

color:
   Red
   Green
   Blue

When loading a product collection how can i load the collection based on either red, blue or green values without knowing the actual option ids?

For example:

Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('color', 'Red');

Will not work as i need to know the option id.

This means loading the attribute and getting the options id – which is going to be innefficient for a large number of attributes/options.

Best Answer

by default you cannot filter by color (or any dropdown attribute) like that. The cleanest way to do it is to get the option id for the red color.

$collection = Mage::getModel('catalog/product')->getCollection();
$options = Mage::getModel('eav/config')->getAttribute('catalog_product', 'color')->getSource()->getAllOptions(); //get all options
$optionId = false;
foreach ($options as $option) {
    if (strtolower($option['label']) == 'red'){ //find the Red option
        $optionId = $option['value']; //get it's id
        break;
    }
}
if ($optionId) { //if there is an id...
    $collection->addAttributeToFilter('color', $optionId);
}

But this could backfire if you have 2 options with the same name.

There is also this option:

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->where('color_value = ?', 'Red');

But it works only when you have the flat catalog enabled and when the color attribute is set to be "Used in product listing".
I don't recommend this approach. It can get you into trouble.