How to filter all products by custom dropdown attribute in magento?

I created my own drop-down attribute with the name " by_item " and added several options to it, for example, Suite, Suite, Jeans, etc.

<?php // get all products $collection = Mage::getModel('catalog/product')->getCollection(); $collection->addAttributeToSelect('*'); //filter codition $collection->addFieldToFilter(array( array('attribute'=>'by_item','eq'=>"Suite"), )); foreach ($collection as $product) { var_dump($product->getData()); } ?> 

He gives nothing :(

but when I do this:

 <?php $collection = Mage::getModel('catalog/product')->getCollection(); $collection->addAttributeToSelect('*'); //filter codition //$collection->addFieldToFilter(array( // array('attribute'=>'by_item','eq'=>"Suite"), // )); foreach ($collection as $product) { echo $product->getName() . "<br />"; } ?> 

he gives me all the names of the products. I visited many articles, but did not meet a single question :(

+4
source share
1 answer

This does not work because you are using the version of OR (nested arrays) addFieldToFilter() .

What you want is version I. Try the following:

 $collection = Mage::getModel('catalog/product')->getCollection(); ->addAttributeToSelect('*') ->addFieldToFilter('by_item', array('eq' => 'Suite')); foreach ($collection as $product) { var_dump($product->debug()); } 

EDIT

It is said that the OP was talking about the "Dropdown" attribute (not the text box).

When using addFieldToFilter() to filter using the addFieldToFilter() -down attribute, you should use the value / id option, but not the text / option label.

For example, if your own drop-down attribute has the following parameters

 id text 12 Suite 13 Bridal 14 Jeans 

and you want to filter "Suite", you can register it as follows:

 $collection = Mage::getModel('catalog/product')->getCollection(); ->addAttributeToSelect('*') ->addFieldToFilter('by_item', array('eq' => '12')); 

You can also indirectly use your text / label:

 $collection = Mage::getModel('catalog/product')->getCollection(); ->addAttributeToSelect('*') ->addFieldToFilter( 'by_item', array( 'eq' => Mage::getResourceModel('catalog/product') ->getAttribute('by_item') ->getSource() ->getOptionId('Suite') ) ); 
+8
source

Source: https://habr.com/ru/post/1398002/


All Articles