The entities
child nodes act primarily as alias names for database table names. They can be used within the context of the various database resource models, which take care of adding any database prefix configured in app/etc/local.xml
.
Using your example, we'll assume we have an admin_log_note
table which has two columns: admin_log_id
and note
<models>
<adminlog>
<class>Rayman_Adminlog_Model</class>
<resourceModel>Adminlog_mysql4</resourceModel>
</adminlog>
<adminlog_mysql4>
<class>Rayman_Adminlog_Model_Mysql4</class>
<entities>
<adminlog>
<table>admin_log</table>
</adminlog>
<adminlog_note>
<table>admin_log_note</table>
</adminlog_note>
</entities>
</adminlog_mysql4>
</models>
If you needed to join the "note" in a collection (e.g. to render a grid) you would do the following:
$collection = Mage::getModel('adminlog/log')->getCollection();
$collection->join(array('log_notes' => 'adminlog/adminlog_note'), 'main_table.id = log_notes.log_id', array('log_notes.note'));
This will create an inner
join in the SQL statement generated. It's possible to do different types of joins (e.g. left) by working with the query select object:
$collection->getSelect()->joinLeft(array('log_notes'=> $collection->getTable('adminlog/adminlog_note')), 'main_table.id = log_notes.log_id', array('log_notes.note'));
When working with the select object it's necessary to explicitly get the table name from a magento resource model (in this case the collection model). The Varien_Db_Select
class is at a different abstraction level than the Mage_Core_Model_Resource_Db_Collection_Abstract
class.
A warning about left joins and collections: It's possible to generate a query which produces multiple rows from the main_table
. The abstract collection classes do not support this and will throw an exception. Be sure you understand the results of the query in this context. Many times the query is written with very little data and will appear to function as inteded. Once more data has been populated this issue crops up and catches developers by surprise in production.