Magento: How to retrieve products with a specific attribute?

Mostly all Models in the Magento have a corresponding Collection object that can be used to fetch multiple instances of a Model.
To instantiate a Product collection, do the following

	$collection = Mage::getModel('catalog/product')->getCollection();

Products are a Magento EAV style Model, so you’ll need to add on any additional attributes that you want to return.

	$collection = Mage::getModel('catalog/product')->getCollection();

	//fetch name and weight into data
	$collection->addAttributeToSelect('name');      
	$collection->addAttributeToSelect('weight');

There’s multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.

The following shows how to filter by a range of values (greater than AND less than)

	$collection = Mage::getModel('catalog/product')->getCollection();
	$collection->addAttributeToSelect('name');      
	$collection->addAttributeToSelect('weight');        

	//filter for products whose weight is greater than (gt) 10
	$collection->addFieldToFilter(array(
	        array('attribute'=>'weight','gt'=>'10'),
	));     

	//AND filter for products whose weight is greater than (lt) 20
	$collection->addFieldToFilter(array(
        	array('attribute'=>'weight','lt'=>'20'),
	));

While this will filter by a name that equals one thing OR another.

	$collection = Mage::getModel('catalog/product')->getCollection();
	$collection->addAttributeToSelect('name');      
	$collection->addAttributeToSelect('weight');        

	//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
	$collection->addFieldToFilter(array(
        	array('attribute'=>'name','eq'=>'Product1'),
	        array('attribute'=>'name','eq'=>'Product2'),            
	));

A full list of the supported short conditionals (eq,lt, etc.) can be found in the _getConditionSql method in lib/Varien/Data/Collection/Db.php

Finally, all Magento collections may be iterated over (the base collection class implements on of the the iterator interfaces). This is how you’ll grab your products once filters are set.

	$collection = Mage::getModel('catalog/product')->getCollection();
	$collection->addAttributeToSelect('name');      
	$collection->addAttributeToSelect('weight');        

	//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
	$collection->addFieldToFilter(array(
        	array('name'=>'weight','eq'=>'Product1'),
	        array('name'=>'weight','eq'=>'Product2'),           
	));

	foreach ($collection as $product) {
        	//var_dump($product);
	        var_dump($product->getData());
	}

Comments

One response to “Magento: How to retrieve products with a specific attribute?”

Leave a Reply

Your email address will not be published. Required fields are marked *

*