Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving two models with foreign key

Tags:

magento

I'm curious whether this is even possible.

Basically I have two related models. I'm wondering if it's possible to save both models as a transaction, automatically populating the foreign key of the second model with the new insert id of the first.

I know that this can be done by saving the models separately, but my question is whether it can be done as one save.

Thanks!

like image 916
Nate Avatar asked Dec 27 '25 16:12

Nate


1 Answers

I ended up doing this by using after/before saves and modifying the data. I passed the id around using the registry.


My Solution

//after first model save
public function _afterSave(){
    Mage::unregister('id');
    Mage::register('id', $this->getData('id'));
}

//before second model save
public function _beforeSave(){
    if (Mage::registry('id') && !$this->getData('id')) {
        $this->setData('id', Mage::registry('id'));
    }
}
like image 171
Nate Avatar answered Dec 31 '25 18:12

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!