I have two multi-select attributes in my Magento 1.9 install (with their respective options) like this:
make
- Manufacturer A
- Manufacturer B
- Manufacturer C
model
- Type A
- Type B
- Type C
I have some products that will have more than one "make" and "model".
How do you load all products from a specific category and filter by products having a specific selected multi-select attribute option in Magento?
I am trying to load products where a scenario like this exists:
make = [Manufacturer A] and [Manufacturer C]
model = [Type A] and [Type B]
This is what I have tried so far:
// Mini-config
$make_attribute_code = 'make';
$model_attribute_code = 'model';
$filter_by_make = 'Manufacturer A';
$filter_by_model = 'Type A';
$load_from_category = 10117;
// Parse attribute option id of "Make"
$make_option_id = null;
$makeAttributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product', $make_attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($makeAttributeId);
$attributeOptions = $attribute ->getSource()->getAllOptions();
foreach ($attributeOptions as $attributeOption) {
if (trim($attributeOption['label']) == $filter_by_make) {
$make_option_id = (int)trim($attributeOption['value']);
break;
}
}
// Parse attribute option id of "Model"
$model_option_id = null;
$modelAttributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product', $model_attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($modelAttributeId);
$attributeOptions = $attribute ->getSource()->getAllOptions();
foreach ($attributeOptions as $attributeOption) {
if (trim($attributeOption['label']) == $filter_by_model) {
$model_option_id = (int)trim($attributeOption['value']);
break;
}
}
// Load category products having selected "Make" & "Model"
$products = Mage::getModel('catalog/category')
->load($load_from_category)
->getProductCollection()
->addAttributeToSelect('*')
->addAttributeToFilter(array(array('attribute' => $make_attribute_code, 'eq' => $make_option_id)))
->addAttributeToFilter(array(array('attribute' => $model_attribute_code, 'eq' => $model_option_id)))
->joinField(
'qty',
'cataloginventory/stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
);
If the product has only one "make" and "model" option selected, it appears to be showing. Any ideas?