rss
twitter
    Find out what I'm doing, Follow Me :)

Monday, January 25, 2010

Pin It

Widgets

A brief introduction to Magento Collection

A collection is a Model type containing other Models, it is basically used in Magento to handle and manipulate product lists.

Let’s have a look at the code!

The first thing to do is to retrieve the products’ model from module Mage/Catalog, and then get the collection of products:

/* Load a collection with all products */
$collection = Mage::getModel('catalog/product')->getCollection()
->load();
foreach($collection as $product) {
var_dump($product->getData());
}

Note that by default, Magento doesn’t load all the attributes.

/* Load a collection with all products and all products' attributes */
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect( '*' )
->load();
foreach($collection as $product) {
var_dump($product->getData());
}

The collection is a powerfull tool that allows you to filter or sort the list according to EAV attributes using the method
addAttributeToFilter():

$collection= Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('entity_id',
array('in'=> array(16,17,19,20) )
)
->load();
foreach($collection as $_prod) {
var_dump($_prod->getData());
}

The following example show how to filter on a particular attribute.

$collection= Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('entity_id',
array('in'=> array(16,17,19,20) )
)
->load();
foreach($collection as $_prod) {
var_dump($_prod->getData());
}

The complete list of short SQL conditions allowed can be found in lib/Varien/Data/Collection/Db.php under method _getConditionSql

You can also specify an amount of product you want to display, using methods setPageSize($size) and setCurPage($page):

$collection= Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->setPageSize(5)
->setCurPage(1)
->load();
foreach($collection as $_prod) {
echo $_prod->getName();
}

On other way to do this is by using limit() method:

$collection=Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*');
$collection->getSelect()->limit(5);
foreach($collection as $item){
echo $item->getName();
}

Note: if you use limit() method to limit collection, you can’t use load() method here, otherwise you will get all products.

Source : http://www.bysoft-technologies.com/blog/magento/a-brief-introduction-to-magento-collection/478

No comments:

Post a Comment