Saturday, June 30, 2012

Retrieve Magento Products with Attribute Value

Magento uses EAV Model to retrieve products, so you'll need to add additional attributes that you want to return.


$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and orig_price into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');

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('orig_price');
//filter for products whose orig_price is greater than (gt) 50
$collection->addFieldToFilter(array(array('attribute'=>'orig_price','gt'=>'50'),));
//AND filter for products whose orig_price is less than (lt) 100
$collection->addFieldToFilter(array(array('attribute'=>'orig_price','lt'=>'100'),));

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


$collection = Mage::getModel('catalog/product')->getCollection();
//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(array('attribute'=>'name','eq'=>'Widget A'), array('attribute'=>'name','eq'=>'Widget B'),));

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('orig_price');
//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection>addFieldToFilter(array(array('name'=>'orig_price','eq'=>'Widget A'),array('name'=>'orig_price','eq'=>'Widget B'),));
foreach ($collection as $product) {
var_dump($product->getData());
}

Solution by Alan Storm

No comments:

Post a Comment