Using collection in Magento for database manipulation

Basically a collection is a model type that contains other model.In other words we can say a collection is basically a set of models in magento. These Models are used to manipulate database as per our requirement. In the past blog I have shared “How to run Custom Mysql Query in Magento” but here in this blog i am demonstrating the same thing but using collection.

With the collection we will get the data from database. Here is the simplest way to do this.

// Creating model object on which we want to do manipulation
$model = Mage::getModel("customer/account_history");
// Generating Collection of above model.
$collection = $model->getCollection();
//We are adding filter on collection that
// we want the data of currently logged in user only.
//Adding where condition into the query
$collection->addFieldToFilter('status', array('neq' => '0'));
// Adding order by clause to the mysql query through collection
$collection->getSelect()->order(new Zend_Db_Expr('created_time DESC'));
// Adding limit to mysql query through collection
//Below code will print full mysql query for you so that you can see it
echo $collection->getSelect();
// Now use your collection. Simply loop through it

Now you can use this above collection to get your intended data

// Looping collection to get data
foreach($collection as $product) {

Hope you understand… Thanks

Related posts:

The following two tabs change content below.

Chandra Shekhar

GCP Architect
Chandra Shekhar Pandey is Google certified Cloud engineer, I am Magento2 Trained developer. Having huge experience in designing cloud solution. I have around 12 years of experience with world enterprise IT companies and fortune 500 clients. During my architecture design I am always caring about high availability, fast performance and resilient system. From the programmer background I have huge experience in LAMP stack as well. Throughout my carrier I have worked on Retail, E-Learning, Video... Read More about Chandra Shekhar

Latest posts by Chandra Shekhar (see all)