Skip to main content

[magento] Product Collection Bible

Magento Product Collection Bible

Adam Moss


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’.
1
$collection = Mage::getModel('catalog/product')->getCollection();
1
$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

1
$collection->getAttributeToSelect('*');

Add Individual Product Attributes

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

Add Specific Price Attributes

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

Add Category IDs to Products

1
$collection->addCategoryIds();

Add Tier Pricing Info

1
$collection->addTierPriceData();

Add Product URL Rewrites

1
$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

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

Is Not Equal To

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

Greater Than

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

Less Than

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

Greater Than or Equal To

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

Less Than or Equal To

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

Contains – with % wildcards

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

Does Not Contain – with % wildcards

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

In Array

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

Not In Array

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

Is NULL

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

Is Not NULL

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

Further Filtering

There are also more general filters that can be applied:

Filter by Product IDs

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

Filter by Current Store

1
$collection->addStoreFilter();

Filter by Current Website

1
$collection->addWebsiteFilter();

Filter by Category

1
$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

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

Order by Attribute Descending

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

Random Order

1
$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.
1
$collection->setPageSize(10);

Count Results

Always useful when checking if any results have been returned.
1
$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!
1
$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.
1
$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!

http://www.creare.co.uk/magento-product-collection-bible

Comments

Popular posts from this blog

Browser User Agent List

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36 Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0 Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0;...

[linux] Adjusting child processes for PHP-FPM (Nginx)

Adjusting child processes for PHP-FPM (Nginx) Problem: The following warning message appears in the logs: [26-Jul-2012 09:49:59] WARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers), spawning 32 children, there are 8 idle, and 58 total children [26-Jul-2012 09:50:00] WARNING: [pool www] server reached pm.max_children setting (50), consider raising it It means that there are not enough PHP-FPM processes. Solution: We need to calculate and change these values based on the amount of memory on the system: /etc/php-fpm.d/www.conf pm.max_children = 50 pm.start_servers = 5 pm.min_spare_servers = 5 pm.max_spare_servers = 35 - the following command will help us to determine the memory used by each (PHP-FPM) child process: ps -ylC php-fpm --sort:rss The RSS column shows non-swapped physical memory usage by PHP-FPM processes in kilo Bytes. On an average each PHP-FPM process took ~75MB of RAM on my machine. Appropriate valu...

[symfony] Assert in Entity

* @Assert\NotBlank() * @Assert\Blank() * @Assert\NotNull() * @Assert\Null() * @Assert\True(message = "The token is invalid") * @Assert\False( *     message = "You've entered an invalid state." * ) * @Assert\Type(type="integer", message="The value {{ value }} is not a valid {{ type }}.") is_ array bool callable float double int integer long null numeric object real resource scalar string ctype_ alnum alpha cntrl digit graph lower print punct space upper xdigit * @Assert\Email( *     message = "The email '{{ value }}' is not a valid email.", *     checkMX = true * ) * @Assert\Length( *      min = 2, *      max = 50, *      minMessage = "Your first name must be at least {{ limit }} characters long", *      maxMessage = "Your first name cannot be longer than {{ limit }} characters long" * ...