Dealing with Magento Model or Collections
As We know that the implementation of a “Models Tier” is a important part of any MVC framework. It represents the data of your application, and most applications are useless without data. Magento Models play an even important role, as they contain the “Business Logic” that’s often relegated to the Controller or Helper methods in other PHP MVC frameworks.
Actually in case of collections in Magento. Collection is a Model type containing other Models, it is basically used in Magento to handle product lists from a category or a bundle option, but not only.
Below is a simple example of loading some product collection from a category and ordering them on their product name using Magento’s API.
$collection = Mage::getModel('catalog/category')->load($categoryId)
->getProductCollection()
->addAttributeToSort('name', 'ASC');
you can sort multiple Fields by using Collection’s method addAttributeToSort.
$collection = Mage::getModel('module/model_name')->getCollection()
->addAttributeToSort('order', 'ASC')
->addAttributeToSort('last_name', 'ASC')
->addAttributeToSort('first_name', 'ASC')
;
You can also pass IF/THEN statements, but be sure to use the proper quotation of your table’s fields.
$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->order( array('IF(`order`>0, `order`, 9999) ASC',
'last_name ASC', 'first_name ASC') );
In this example, the table will be sorted by the order field, then by last name, then by first name, where order is greater than zero, followed by order being equal to or less than zero, all ascending.
You can also join Tables in your Magento model. you can easily add SQL joins to a select statement.
$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join( array('table_alias'=>$this->getTable('module/table_name')), 'main_table.foreign_id = table_alias.primary_key', array('table_alias.*'), 'schema_name_if_different');
In this example the join method takes an array of alias⇒table_name key pairs, then a standard join clause using `main_table` to refer to the original select, then an array of fields to be retrieved in the join, a different schema can be specified as a last parameter.
Follow @phpzag

I’m very happy to discover this web site. I wanted to thank you for ones time due to this fantastic read!! I definitely enjoyed every little bit of it and i also have you bookmarked to look at new stuff in your blog.