SQL – How to Load Model Data Joining 2 Tables

modelsql

Suppose I have a simple Model A that target table A now I have to add some extra info so I decide to create a Model B and save those extra info in a Table B with a foreign key pointing to Table A index key.

Usually Joins are done in collections but if I load a model the collection is not called, instead only the resource model is used.

How can I modify Model A to load also data from Table B on load()?

Best Answer

Inside resource model class add following function

protected function _getLoadSelect($field, $value, $object)
{
    $select = parent::_getLoadSelect($field, $value, $object);

    $select->joinLeft(
        array('t_b' => 'table_b'),
        $this->getMainTable() . '.id = t_b.id',
        array('columnA'));
    return $select;
}

When you called Mage::getModel('modulename/TableA')->load(1), this method will join with table_b.

Related Topic