1

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?

1
  • 1
    So at this point the first table contains the value that is required in the second table? Did you try to run the save code for the second file all by itself to see if it really worked? Can you show some code for what you are trying?
    – Dan
    Sep 25, 2013 at 16:16

1 Answer 1

4

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.

1
  • That has worked and i've placed it in my saveAction, although after looking at the Mage_Customer_Model_Resource_Customer I wondered if it would be better to place this code in my model in a _beforeSave or _afterSave function? and make all the necessary validation checks in _before save and update table2 after save? I ask as I can imagine if it is the way to go, for me, to get it to work it will take me hours.
    – tony09uk
    Sep 26, 2013 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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