Filter Products By Attribute With NULL values In Magento

Monday, 30. September 2013

One little tip for someone who wants to select a set of items or products in Magento based on attribute with a NULL value.

$collection = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToFilter('ATTRIBUTE_CODE', array('null' => true)) 
    ->getAllIds();

Magento: Add an OR condition to addAttributeToFilter method programatically

Tuesday, 26. July 2011

If you have ever wondered how to get an OR clause on Magento while pulling a certain collection this post may help you!

The easy way is to use the IN clause and pass through an array of values.

 
        $collection = Mage::getModel('catalog/product')->getCollection()
                ->addAttributeToSelect('*')
                ->addCategoryFilter($category)
        # add and OR condition on material
        ->addAttributeToFilter('material', array('IN' => array(val1, val2, val3,...)))
        ->load();

You will then get something that looks similar to this output

SELECT `e`.*, `cat_index`.`position` AS `cat_index_position`, IF(_table_material.value_id>0, _table_material.VALUE, _table_material_default.VALUE) AS `material` FROM `mag_catalog_product_entity` AS `e` INNER JOIN `mag_catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id='1' AND cat_index.category_id='367' AND cat_index.is_parent=1 INNER JOIN `mag_catalog_product_entity_int` AS `_table_material_default` ON (_table_material_default.entity_id = e.entity_id) AND (_table_material_default.attribute_id='122') AND _table_material_default.store_id=0 LEFT JOIN `mag_catalog_product_entity_int` AS `_table_material` ON (_table_material.entity_id = e.entity_id) AND (_table_material.attribute_id='122') AND (_table_material.store_id='1') WHERE (((((IF(_table_material.value_id>0, _table_material.VALUE, _table_material_default.VALUE) = '138')<strong> OR </strong>(IF(_table_material.value_id>0, _table_material.VALUE, _table_material_default.VALUE) = '134')))))

The method accept arrays of attributes as well and this can be great for making your code neater like this:

$collection->addAttributeToFilter(
  array(
      array('attribute'=>'material', 'eq'=>'silk'),
      array('attribute'=>'brand', 'neq'=>'13')
    )
  );

You can also tell Magento what kind of join to use by supplying the third argument of the method addAttributeToFilter like so

$collection->addAttributeToFilter(
  array(
      array('attribute'=>'material', 'eq'=>'silk'),
      array('attribute'=>'brand', 'neq'=>'13')
    ),
    '',
    'left'
  );