With CakePHP 3, I have 2 models : Inscriptions and Tests:
Inscriptions hasMany Tests
I have an afterSave() callback in InscriptionsTable, where I create the Tests for the new Inscription :
public function afterSave($event, $inscription, $options) {
// find out which tests I need to create (based on Inscription fields)
$tests = ...;
foreach($tests as $t) {
$test = $testTable->newEntity([
...
'inscription_id' => $inscription->id
]);
$testTable->save($test)
}
}
...so when an Inscription is saved, all the needed related tests are created too and they reference the Inscription.
It's working fine, but now I noticed that when I save a new Inscription, the afterSave callback is fired multiple times. It seems that it fires one time for the Inscription entity, and fires again for each Test created, like if the line
$testTable->save($test)
...triggers the InscriptionsTable::afterSave() callback.
I tried to add ['callbacks' => FALSE] as second parameter for save() (like in CakePHP 2), nothing changed.
What could be happening here ?
Thanks
EDIT
Konstantinos Daskalopoulos answer is correct (and accepted), full explanation on http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-entities, point 6. on the list "When an entity is saved a few things happen" ("6. Parents associations are saved"). So I guess it explains what I see.
\Cake\Error\Debugger::trace()) in your callback so that you can actually figure out why/from where the callback is being invoked. Also note that there is nocallbacksoption in CakePHP 3. btw, you could also usebeforeSaveinstead to create the associated data on the main entity, and let Cake save everything at once. - ndm