Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

visibility = 4 made it tricky. Commented it out and size filter worked fine.

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

Try this way:

$filter = array(
    'attribute' => 'size',
    'in'        => array(3),
    );

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

Haven't tested, but should work. Hope this helps. Ref.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top