8

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()?

  • Good Question...I like it – Amit Bera Jul 8 '14 at 11:54
  • It is a kind of EAV simple implementation ... I found a kind of solution but I'm waiting for other approach and test it, before posting it – Fra Jul 8 '14 at 12:00
10

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.

  • I think limit(1) is not required:joinLeft() will be enough ... – Fra Jul 8 '14 at 14:37
  • I just set an example for that. You can change this according to your requirement. – Sohel Rana Jul 8 '14 at 15:07
5

I can propose you the approach that I use, and it is quite easy.

Steps:

  1. Rewrite resource model of Model A (If Model A is yours model and not Magento then you can skip this step)

  2. Rewrite method _getLoadSelect() of resource model of Model A. Select query is generated in this method and here you can join your the other tables.

  • You beat me to it. +1 – Marius Jul 8 '14 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.