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.
$collection->addCustomerFilter(Mage::registry('current_customer')->getId());
//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
$collection->getSelect()->limit(100);
//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
$this->setCollection($collection);

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

// Looping collection to get data
foreach($collection as $product) {
var_dump($product->getData());
}

Hope you understand… Thanks

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 Conferencing and social media domain. The motive of creating cutehits was just to share the knowledge/solutions I get to know during my day to day life so that if possible I can help someone for same problems/solutions. CuteHits.com is a really a very effort for sharing knowledge to rest of the world. For any query/suggestion about same you can contact me on below details:- Email: shekharmca2005 at gmail.com Phone: +91-9560201363

Latest posts by Chandra Shekhar (see all)

You may also like...