Save 2 objects with a reference to each other in one transaction
-
13-12-2019 - |
Question
for some security reasons I try to save 2 custom objects (different models) into the database, via:
try {
$transaction = Mage::getResourceModel('core/transaction')
->addObject($object1)
->addObject($object2);
$transaction->save();
} catch (Exception $e) {
echo $e->getMessage();
}
The problem is, that the database table of $object2 contains a reference id to $object1, but this is auto incremented in $object1 and unknown at this point.
To visualize my problem:
database table of $object1:
entity_id | ... | ...
-----------------------------
1234 | ... | ...
the database table of $object2 should looks like this:
entity_id | object_1_id | ...
---------------------------------
5678 | 1234 | ...
How can I get the auto incremented id of $object1 and save within the same transaction to $object2 table? Is it possible? Makes that sense?
Thanks for help.
Solution
It looks to me like you have a "one to many" relation here. $object1
can have associated 0, 1, 2...,n instances of $object
2.
So you can say that $object1
is a parent entity for $object2
.
you can handle the save of both parent and child entities in the same transaction like this.
Let's say that the class (Model) for $object1
is called ParentObject
and the class (model) for $object2
is ChildObject
.
In ParentObject
add this member:
protected $childObjects = array();
a method called addChildObject
.
public function addChildObject(ChildObject $childObject)
{
$this->childObjects[] = $childObject;
return $this;
}
Magento has callbacks that are executed for each save
method call from any model.
So you need to implement one of these methods called _afterSave
in the ParentObject
class. This one is called after saving the ParentObject
instance, so you have an ID you can use.
protected function _afterSave()
{
foreach ($this->childObjects as $childObject)
{
//set the $object1Id (the FK value) for child objects and save them
$childObject->setObject1Id($this->getId());
$childObject->save();
}
return parent::_afterSave();
}
Now all you have to do in your code is:
$object1->addChildObject($object2);
$object1->save();
and everything will be saved in the same transaction.