3 models mapping 3 tables: Image, Slider and SliderImageAssoc. In this case it’s one-to-many, as one Image can be “linked” to many Sliders.
The ZF way, which I’m accustomed to, also proposes 3 models, and, with special internal data stored in them, you can do things like $imageRow->getSliderViaSliderImageAssoc(), resulting the parent row of Slider of that certain Image model.
My question is how exactly does one fetches related models in Magento? I’ve seen methods named setParentFieldName, but I don’t think they were in core. Can you do things like:
foreach ($model->getCollection() as $model) {
$parentRow = $model->getParent('some/model/name');
$dependentRowset = $model->getChildren('some/other/model/name');
}
PS: I don’t necessarily want to use the ZF style of fetching.
In Magento there is no support for generic mapping of entity table relationships as far as I know. I suggest adding helper methods to the resource model and resource collection to add the joins to the select object if required.
Here is an examples from the core of the mentioned utility method approach to load additional data on a collection:
If called, the
core_url_rewritetable is joined with the product entity table.If the joined data needs to be loaded every time, the
_getLoadSelect()method can be used for resource models, or_initSelect()for collections.Here is an example for that from the
cms/pageresource model:An example for an
_initSelect()join can be found inMage_CatalogInventory_Model_Resource_Stock_Item_Collection::_initSelect()(I’ll won’t post it here because it is so similar to the_getLoadSelect()example).Some modules set joins on collections from “outside” the module, i.e. the stock item collection
Mage_CatalogInventory_Model_Resource_Stock_Item::addCatalogInventoryToProductCollection($productCollection). Here thecataloginventorymodule uses the product collections select object to add some joined data.Finally, another approach is to load the required data in the
_afterLoad()method doing a separate select (as compared to a join):This can be also done using an
*_load_afterevent for collections or models.