This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join the live AMA session with Adam Silverstein on open source and WordPress core! Register Now →

Use These Magento Product Collections Instead of SQL

Updated on December 24, 2021

3 Min Read

At some point, a Magento developer has to deal with Magento Model Collections. Magento collections represent an efficient way of grouping models together and it’s an easy option of grabbing a group of models from the database with almost little to no SQL code (thanks to its unique methods). Collections are tricky to work with, but they offer extensive data about products, customers, categories, attributes, etc.

Magento Product Collections

In this article, I will cover some useful methods of loading the Product Collection, adding Attributes to Collections, filtering and sorting Collection, etc.

Let’s dive into it.

Loading Product Collection in Magento

There are two ways of loading product collection:

Call getCollection() method in the product model instance:

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

Load collection class in the getResourceModel() factory method:

$collection = Mage::getResourceModel('catalog/product_collection');

Cloudways Magento Hosting For Developers

Adding Attributes to a Collection in Magento

The product model is a huge set of data and calling more attributes in the collection usually takes a lot of time to load. By default, Magento only loads the simple data found in the catalog_product_entity table, which includes IDs, SKUs, Entity Type IDs, etc.

You can also check out how to configure Magento Attributes blog post.

Check out these convenient methods for adding further product attributes:

Add All Attributes

$collection->addAttributeToSelect('*');

Add Individual Attributes

$collection->addAttributeToSelect('name');

Add Multiple Attributes

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

Filtering Collections in Magento

Magento is an EAV system that gives access to the addAttributeToFilter() method which can take a larger range of arguments as compared to the general addFieldToFilter() filter method.

Equals To

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

Not Equals To

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

Greater Than

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

Less Than

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

Equals To OR Greater Than

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

Equals To OR Less Than

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

Is Null

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

Is Not Null

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

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)));

Does Contain (Including % Wildcard)

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

Does Not Contain (Including % Wildcard)

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

Sorting Collections in Magento

You can also sort a collection in Magento by attributes in ascending, descending or random order.

Ascending Order

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

Descending Order

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

Random Order

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

Limiting Collection Results in Magento

If you want to limit the product collection results to a certain number, use the following method. You only need to pass a number as an argument.

$collection->setPageSize(8);

Debugging Collections in Magento

If you need to debug a collection and wish to know why it is continuously returning a particular set of results, use this debugging method and print the query that is hitting the database.

$collection->getSelect();

Conclusion

The Magento Model Collections essentially make data modeling and filtering very easy without passing any MySQL queries. The good thing is that the Magento platform handles this “magic” on its own without requiring third party extensions. In this article, I have just scratched the surface and there are still a number of functions which would greatly help you in Magento projects by saving a lot of time that you would otherwise waste on writing complex SQL queries.

If you need help, do leave a comment and I will get back to you ASAP.

 

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdur Rahman

Abdur Rahman is the Magento whizz at Cloudways. He is growth ambitious, and aims to learn & share information about Ecommerce & Magento Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now