Wednesday, 19 October 2011

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.

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

No comments:

Post a Comment