Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
    );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...