Search code examples
attributesmagentofilterexistsnot-exists

Magento: addAttributeToFilter but ignore for products that don't have this attribute?


I'm trying to show add some filters on my store, but they have a nasty side effect.

Suppose I have product type A and B. Now I want to only show A where color = blue/red.

$collection = Mage::getResourceModel('catalog/product_collection')
    ->setStoreId($this->getStoreId())
    ->addCategoryFilter($this)
    ->addAttributeToFilter(array(
          array('attribute' => 'color', 'in' => array(4, 6)),
    )
    );

This does the trick, but now because product type B has no value assigned to color(since this attribute isn't appointed to it) no products for this type show up.

I had found this code on the forum http://www.magentocommerce.com/boards/viewthread/178309, but it doesn't work:

array('attribute' => 'color', 'is' => new Zend_Db_Expr('null'))

Neither does:

array('attribute' => 'color', 'null' => true),

That actually shows products which have the attribute assigned but with no value declared...

I also tried adding:

array('attribute' => 'price', 'gteq' => 0), 

Because I figured these statements were connected with 'OR' (according to the documentation) but even that only adds product types which have the attribute assigned...

Note that these values come from a drop down list, not sure if that matters though.


Solution

  • Maybe it's too late, but this works for me:

    $collection = Mage::getResourceModel('catalog/product_collection')
        ->setStoreId($this->getStoreId())
        ->addCategoryFilter($this)
        ->addAttributeToFilter(
            array(
                array('attribute' => 'color', 'null' => true),
                array('attribute' => 'color', 'in' => array(4, 6)),
            ),
            '',
            'left'
    );