Almost all Magento models have a corresponding Collection object that can be used to retrieve multiple instances of the model.
Follow these steps to create an instance of the product collection.
$collection = Mage::getModel('catalog/product')->getCollection();
The products are a Magento EAV style model, so you need to add any additional attributes you want to return.
$collection = Mage::getModel('catalog/product')->getCollection(); //fetch name and orig_price into data $collection->addAttributeToSelect('name'); $collection->addAttributeToSelect('orig_price');
There are several syntaxes for setting filters in collections. I always use the detailed below, but you can check the Magento source for additional ways to use filtering methods.
The following shows how to filter a range of values โโ(more and less)
$collection = Mage::getModel('catalog/product')->getCollection(); $collection->addAttributeToSelect('name'); $collection->addAttributeToSelect('orig_price'); //filter for products whose orig_price is greater than (gt) 100 $collection->addFieldToFilter(array( array('attribute'=>'orig_price','gt'=>'100'), )); //AND filter for products whose orig_price is less than (lt) 130 $collection->addFieldToFilter(array( array('attribute'=>'orig_price','lt'=>'130'), ));
For now, it will be filtered by a name that is equal to one or the other.
$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('attribute'=>'name','eq'=>'Widget A'), array('attribute'=>'name','eq'=>'Widget B'), ));
A complete list of supported short conditional expressions (eq, lt, etc.) can be found in the _getConditionSql method in lib/Varien/Data/Collection/Db.php
Finally, all Magento collections can be iterated (the base collection class implements iterator interfaces). This is how you will capture your products after installing filters.
$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); var_dump($product->getData()); }