How do I filter a magento collection by a select drop-down attribute?

Benubird picture Benubird · Feb 8, 2013 · Viewed 18.8k times · Source

In magento, I have an attribute called cl_designer, which is a select drop-down option. I want to filter the products collection on it, like this:

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('cl_designer', array('like' => $filter));

But it doesn't work! When I print out the query with $collection->getselect(), I see that it is comparing $filter to catalog_product_entity_int.value. But this is wrong, because for select options, catalog_product_entity_int.value is the option_id, NOT the value. So how do I make it filter on the actual option value?

Answer

Jürgen Thelen picture Jürgen Thelen · Feb 9, 2013

Assuming an example drop-down attribute named size contains the following options:

id    value
22    'small'
23    'medium'
24    'large'

and you want to filter your collection by 'medium' options:

Filter by drop-down option value

To filter a product collection by option value of a product's (custom) drop-down attribute:

$sAttributeName = 'size';
$mOptionValue = 'medium';
$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('*')
    ->addFieldToFilter(
        $sAttributeName,
        array(
            'eq' => Mage::getResourceModel('catalog/product')
                        ->getAttribute($sAttributeName)
                        ->getSource()
                        ->getOptionId($mOptionValue)
        )
    );

Filter by drop-down option id

To filter a product collection by a option id of a product's (custom) drop-down attribute:

$sAttributeName = 'size';
$mOptionId = 23;
$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('*')
    ->addFieldToFilter(
        $sAttributeName,
        array('eq' => $mOptionId)
    );