Filter a collection when the attribute value is not set

Since the very first time I started working with collections in Magento I run into situations where I needed to filter a collection by an attribute whose value is not set yet (for example, when the attribute is of the type ‘yes/no’, values 0/1). If I wanted to filter by all the products with a value ‘1’, that was easy, but when I was on the case of filtering by ‘0’, then the collection filter wouldn’t work properly in the cases the attribute was not yet set.

Here is the solution:

 
 
  1. $collection = Mage::getModel('catalog/product')->getCollection()
  2.             ->addAttributeToFilter(array (
  3.                 array( 'attribute' => 'your_attribute', 'equal' =>'null'),
  4.                 array( 'attribute' => 'your_attribute', 'equal' => '0')
  5.             ));

Leave a Reply

Your email address will not be published.