4

I'm having troubles using addAttributeToFilter on Magento Multiple select attributes.

I have a multiple select attribute for car makes, so the content is 'Audi', 'BMW' and so on. In my example I have a tyre product which I have selected 5 makes for from the multiple select.

I want to display products which have the make 'BMW' as one of their selected fields.

I have tried the following all of which are not working:

$products->addAttributeToFilter('make', array('like' => '%BMW%'));  
$products->addFieldToFilter('make', array('like' => '%BMW%'));  
$products->addAttributeToFilter('make', array('like' => '%38%')); // id of the attribute option

Nothing seems to work.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Adam Moss
  • 5,582
  • 13
  • 46
  • 64
  • Does $products->addAttributeToFilter(’make’, ‘38’) or $products->addAttributeToFilter('make', array('eq', 38)); give you anything? – Alex Hadley May 09 '12 at 16:18
  • It doesn't work. As it's a multiple select attribute Magento creates 'make' as a string like this: 28,30,35,38 - so if I need to filter the products by BMW which is id 38, then I need it to check all those values. – Adam Moss May 09 '12 at 16:25
  • 1
    Would `finset` me an option? Something like `$products->addAttributeToFilter("make", array("finset"=>"38"));` – Alex Hadley May 09 '12 at 16:28

2 Answers2

12

The solution is to use a Find In Set query such as:

$this->_productCollection->addAttributeToFilter("make", array("finset"=>"38"));

A discussion can be seen here: http://www.magentocommerce.com/boards/viewthread/201312/

And a list of different options: http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections

Clonkex
  • 3,373
  • 7
  • 38
  • 55
Alex Hadley
  • 2,125
  • 2
  • 28
  • 50
  • I found out that this will work for regular drop downs as well, not just a multiselect. I am not sure if there is speed reduction for regular dropdowns or not. tested on ee 1.14.2 – Joshua Pack Jul 30 '15 at 20:08
  • I have to login to vote this answer. Thanks for saving my day. – chinhnguyen Sep 03 '21 at 03:07
0

Try bellow syntax finset it working for me.

$collection->addAttributeToFilter($attribute,
    array(
        array('finset'=> array('237')),
        array('finset'=> array('238')),
        array('finset'=> array('239')),
    )
);