Magento – save to multiple tables

database

For the last four hours I have been trying to save data to two tables. I realise that this should be a simple task, due to Magento's style of saving data, but I cannot work out how to do it.

On a previous practice module I put together some code that worked(I must have changed something as it does not work now). The code I did write seemed to be very smelly code and this time I want to do things the right way.

I can save data to a single table, but what I am unable to work out is how to use the id from table 1 and apply that to table two as the foreign key? also does it go in a save action in the controller or is it put somewhere else?

Best Answer

There are multiple ways to save data to two tables at a time.

If you've registered the resource (table-backed) model in Magento's ORM you should be able to do something to the effect of:

$table1 = Mage::getModel('yourmodel/table1');
$table1->setData(array('some'=>'stuff','in'=>'here'));
$table1->save();

Wash, rinse, repeat for the second table - assuming you have a column called parent_id:

$table2 = Mage::getModel('yourmodel/table2');
$table2->setParentId($table1->getId());
$table2->setData($table1->getData());
$table2->save();

This accomplishes your goal of having a table2 related to table1 by the primary key.

Another thought is that if your RDBMS (MySQL?) has the concept of a trigger, you could set up a trigger.