Now we have a "model" instance full of data. We can then change this data (using the magic getters and setters ) and simply call the save() function on the "model". This uses the "resource model" to save the data to the database (automatically figuring out if it should be an INSERT or an UPDATE).
Now how in the heck do we use a "collection model"? Easy.
After we have an instance of the Super_Awesome_Model_Example "model" we can just call the getCollection() function on it. This uses the class alias for the collection that we stored (back when we called the constructor) to get an instance of the "collection model".
One thing that confused me at first was that getCollection() only returned an EMPTY instance of the "collection model"; there was no data in it. To get the data, we need to call the load() function on the "collection model". This can be done directly, or indirectly through the getItems() function. After the load() function is called, the $_items variable is now populated with a bunch of data-filled "models".
HINT: If you are trying to figure out what SQL is running when you call the load() on the collection, you can pass in ->load(true, true) and it will print the SQL to the screen AND a log file.
NOTE: If the collection is a part of the EAV structure, the "models" will ONLY have data from the entity table. To get the rest of the data, you will need to call the load() function on each model, passing in its own ID.
The benefit of using the "resource models" and "collection models" are it's ubber-rich helper functions for generating the SQL. Below, I will list a few of the helpful functions and give a super brief description of what they do. Note, some of these functions are up in the parents/grand parents of the "resource model" and "collection model" classes.
Varien_Data_Collection_Db->addFieldToFilter($field, $condition=null)
1
2
3
|
$collection
->addFieldToFilter(
'name'
,
'example1'
);
$collection
->addFieldToFilter(
'name'
,
array
(
'like'
=>
'example%'
));
$collection
->addFieldToFilter(
'name'
,
array
(
'in'
=>
array
(
'example1'
,
'example2'
)));
|
Mage_Eav_Model_Entity_Collection_Abstract->addAttributeToFilter($attribute, $condition=null, $joinType='inner')
1
|
$collection
->addAttributeToFilter(
'color'
,
'blue'
);
|
Mage_Core_Model_Mysql4_Collection_Abstract->join($table, $cond, $cols='*')
1
|
$collection
->join(
'other_table'
,
'e.id = other_table.fid'
,
array
(
'column1'
,
'column2'
));
|
Varien_Data_Collection_Db->addOrder($field, $direction = self::SORT_ORDER_DESC)
1
|
$collection
->addOrder(
'sequence'
,
'ASC'
);
|
One final thing to say...
There are events that are dispatched before and after EVERY load, save, and delete in both the "models" and the "resource models". This should give you PLENTY of places to hook in if you should need to change the way a specific table needs to be interacted with.