Magento Product Collection Biblde

Magento Product Collection Bible

Any developer who uses Magento will have at some point found themselves deep in model collections, and none more so than the product resource collection.

In this post I cover all the angles with regards to loading your product collections, filtering, sorting and modifying them. This is the Magento Product Collection Bible. Amen to that.

Load Product Collection

There are two basic ways of loading your product collection. Either call method getCollection() on your product model instance or load collection class in the factory method ‘getResourceModel’.

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

Add Attributes To Collection

The product model is an enormous data set, and the more attributes we include in the load the longer it will take. By default, Magento will only load the basic data found in the ‘catalog_product_entity’ table (ID, SKU, Entity Type ID etc…)

Add All Product Attributes

$collection->getAttributeToSelect('*');

Add Individual Product Attributes

$collection->addAttributeToSelect('name', 'description', 'brand');

Add Specific Price Attributes

$collection->addMinimalPrice();
$collection->addFinalPrice();
$collection->addTaxPercents();

Add Category IDs to Products

$collection->addCategoryIds();

Add Tier Pricing Info

$collection->addTierPriceData();

Add Product URL Rewrites

$collection->addUrlRewrite();

Filter Collection

Being an EAV entity type means that we have access to the wonderful ‘addAttributeToFilter()’ method in addition to the standard ‘addFieldToFilter()’, which can take a larger range of arguments.

The following are basic conditional filters, like you’d use in a MySQL query:

Is Equal To

$collection->addAttributeToFilter('status', array('eq' => 1));

Is Not Equal To

$collection->addAttributeToFilter('visibility', array('neq' => 1));

Greater Than

$collection->addAttributeToFilter('price', array('gt' => 3));

Less Than

$collection->addAttributeToFilter('price', array('lt' => 3));

Greater Than or Equal To

$collection->addAttributeToFilter('price', array('gteq' => 4));

Less Than or Equal To

$collection->addAttributeToFilter('price', array('lteq' => 4));

Contains – with % wildcards

$collection->addAttributeToFilter('sku', array('like' => 'DVD%'));

Does Not Contain – with % wildcards

$collection->addAttributeToFilter('sku', array('nlike' => 'ABC%'));

In Array

$collection->addAttributeToFilter('entity_id', array('in' => array(1,3,12)));

Not In Array

$collection->addAttributeToFilter('entity_id', array('nin' => array(1,2,12)));

Is NULL

$collection->addAttributeToFilter('description', 'null');

Is Not NULL

$collection->addAttributeToFilter('description', 'notnull');

Further Filtering

There are also more general filters that can be applied:

Filter by Product IDs

$collection->addIdFilter(array(4,5,6));

Filter by Current Store

$collection->addStoreFilter();

Filter by Current Website

$collection->addWebsiteFilter();

Filter by Category

$collection->setStoreId($id)->addCategoryFilter($category)

Sort Collection

Again, as with MySQL you can sort your collection by a chosen attribute in either ascending or descending order.

Order by Attribute Ascending

$collection->setOrder('price', 'ASC');

Order by Attribute Descending

$collection->setOrder('name', 'DESC');

Random Order

$collection->setOrder('rand()');

Limit Collection

If you’re in a situation where you want your product collection, but want to limit the number of results to a certain amount you can use the ‘setPageSize()’ method, and simply pass in your limit.

$collection->setPageSize(10);

Count Results

Always useful when checking if any results have been returned.

$collection->count();

Return Only Product IDs

Sometimes you’ll just need to get product IDs from your collection, rather than the rest of the product data. By Using ‘getAllIds’ you will receive a nice little array of product IDs for you to do with as you wish!

$collection->getAllIds();

Debug Collection

Want to know why your collection keeps returning results? Using the ‘getSelect()’ method on your collection you can print the MySQL query that is getting sent to the database.

$collection->getSelect();

The model-collection classes in Magento are extremely powerful and make data querying and filtering very easy, without any MySQL knowledge. Thanks for reading!