1

I am having problems with saving data with associated. The problem is that i'm do thing on AfterSave and the associations are triggering the AfterSave before the principal entity($toSave). This is normal? It's like first save the associations then the principal entity. Is a way of changing the order of saving? Makes sense?

$toSave = $this->{MODEL_NAME}->patchEntity($toSave, $postData, ['associated' => ['SomeAssociation']]);
if ($this->{MODEL_NAME}->save($toSave)) {

}

Version: Cakephp 4.x

Thank you.

TacticJuls
  • 304
  • 1
  • 8
  • 1
    That depends on the type of association. "Parent" records (those that do _not_ store the foreign keys) are saved before the root entity is saved, "child" records (those that _do_ store the foreign keys) are saved after the root entity has been saved. In order for someone to give a good answer, you'll have to provide more information about your association configuration, your saving logic, your intention, eg why are you saving x in after save, and what exactly is happening that causes a problem for you that leads you to think you might need to change the order of save operations. – ndm Apr 28 '22 at 23:45
  • Thank you @ndm. The Relationship is BelognsToMany for example: TableA - tableA_tableB - TableB When i save TableA with Associated TableB this wil genereate a record over the tableA_tableB. So, on the AfterSave of each i generate a record in a LogTable and i received as first record the save of the tablea_tableb and after that i have save of the tableA . Makes sense?? – TacticJuls Apr 29 '22 at 13:04
  • You'd need to show the relevant code, just from that description I cannot tell whether what's happening is correct or not. Generally `belongsToMany` records are saved _after_ the root entity, so what you're seeing might be incorrect, but it really depends on your specific implementation. – ndm Apr 30 '22 at 12:15

0 Answers0