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
Chandra Shekhar
Latest posts by Chandra Shekhar (see all)
- Best practices for micro service design - January 23, 2022
- Spring Boot - January 23, 2022
- Java - January 23, 2022
Recent Comments