You get a bonus - 1 coin for daily activity. Now you have 1 coin

Working with the Product Collection in Magento

Practice



Any developer working with the Magento CMS sooner or later has to dive into model collections. Very often you have to work with the product resource collection. In this article we'll go over the basics of loading, filtering, sorting, and modifying this collection.

Loading the product collection
There are two main ways to load the product collection. Using the getCollection() method from a product model instance, or loading the collection class via the getResourceModel() factory method.

Adding attributes to the collection
A product model is a huge set of data. The more model attributes are used in a selection, the longer it will take to execute. By default, using the methods mentioned above, Magento CMS only loads the base data found in the table

To add all attributes, use:

For individual attributes:

For specific attributes:

Add category ID to products:

Tier pricing:

Add URL Rewrites to products:

Filtering results
Using the EAV entity type of the system, you can access the amazing 'addAttributeToFilter()' method. For example:

you can also write it as:

This method is used as a supplement to the standard 'addFieldToFilter()' method from the Zend library Varien_Data_Collection_Db and accepts a large number of arguments. These arguments are represented as expressions and are similar in nature to SQL queries. Here is an example of such expressions in Magento and their equivalent use of data selection (SQL) with the 'WHERE' keyword:

Filter by current store:

Filter by current website:

Filter by category:

Sorting the collection
Again, as with SQL, you can sort the collection by a chosen attribute in ascending or descending order.
Ascending order:

Descending order:

Random order:

Limiting the selection
If a situation arises where you need to limit the number of products in the loaded collection, you can use the 'setPageSize()' method:

Number of products
It's always useful to check whether any results came back after loading the collection and how many products are in the collection:

Debugging the collection
Want to know why and how the collection returns results? By calling the 'getSelect()' method on the collection, you can output all the MySQL queries that are sent to the database.

Model collection classes in Magento are extremely powerful tools that significantly simplify running queries and filtering data, even without any knowledge of MySQL.

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)