Magento: Work With Product Collection

Hello friends,

At last week while working with magento store, we had a requirement to list out products after different filter. Like list out products according to particular category and attributes.

To satisfy our requirement we searched the web and found a proper solution, which is discussed below.

Magento uses a model type called collection, which is containing other models.

And mainly in magento a collection is used to handle product lists, but it is not the only purpose of collection.

Basically in magento we get a product collection by either category model or by product model.

So first of all we need to get category or product model and the syntax to get particular model is as under:

$collection = Mage::getModel('module/model_name');

Here, if we got category model then we can get products of particular category in product collection.

And if we got product model then we can get all the products of store in product collection.

While getting the product collection we can filter it by attribute or field and can sort it by attribute or field.

For Example:

$category_product_collection = Mage::getModel('catalog/category')->load($categoryid)
->addAttributeToFilter('manufacturer', $manufacturerid)
->addFieldToFilter('entity_id', $productid)
->addAttributeToFilter('visibility', $visibility)
->addAttributeToFilter('status', 1)
->addAttributeToSort('name', 'ASC')
->setOrder('created_at', 'desc');

In above example we load the category model and got the product collection of particular category.

And filtered the product collection according to manufacturer, visibility and status attributes and entity_id field, and also sort it by name attribute and created_at field.

Hope this will help you.


Speak Your Mind

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: