Magento – How to Filter Product Collection with Configurable Product Attributes

collection-filteringdropdown-attributefilterproduct-collection

Now I'm trying to filter product collections with my configurable product attribute i.e size

$collection = Mage::getModel('catalog/product')
              ->getCollection()
              ->addAttributeToSelect('*')
              ->addAttributeToFilter('visibility','4')
              ->addAttributeToFilter('size','3');

Above code doesn't works. Apart from attribute size i can able to filter this collection with any attributes like name, sku, created_date etc.

Did anyone know where i'm doing wrong ?

Best Answer

Figured it out by myself.

Above code returns nothing because attribute (size) is assigned only to simple products (associated products) and all simple product's visibility is set to 1 i.e, not visible individually.

Step 1 : Remove visibility to 1, now i can get list of all simple products (associated products) which is assigned to size 3.

Step 2 : Join table catalog_product_super_link to get parent product associated with it.

Complete code is,

    $collection = Mage::getModel('catalog/product')->getCollection()
        ->addAttributeToFilter(
            array(
            array('attribute'=> 'color','like' => '12')
            )
        )
        // multiple filters can be achieved by adding another filterattribute
        ->addAttributeToFilter(
            array(
            array('attribute'=> 'size','like' => '3')
            )
        );

   $collection->getSelect()->joinLeft(array('link_table' => 'catalog_product_super_link'),'link_table.product_id = e.entity_id',
            array('product_id','parent_id')
        );

   $collection->getSelect()->group('link_table.parent_id');

   foreach($collection as $product) {
        $ids[] = $product->getParentId();
       }

    $collection->load();

    echo json_encode($ids);

Hope this may help to someone.