CakePHP 3回调系统和相关实体

时间:2016-06-13 12:36:44

标签: cakephp cakephp-3.0

使用CakePHP 3,我有2个模型:铭文和测试:

Inscriptions hasMany Tests

我在InscriptionsTable中有一个afterSave()回调,在那里我为新铭文创建了测试:

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)

  }
}

...所以当保存铭文时,也会创建所有需要的相关测试,并且它们会引用铭文。

它工作正常,但现在我注意到当我保存新的铭文时,多次触发afterSave回调。它似乎会为Inscription实体触发一次,并为每个创建的Test再次触发,就像行

一样
$testTable->save($test)

...触发InscriptionsTable :: afterSave()回调。

我尝试添加['回调' => FALSE]作为save()的第二个参数(如在CakePHP 2中),没有任何改变。

这里可能会发生什么?

由于

修改

Konstantinos Daskalopoulos answer是正确的(并接受),完整的说明 http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-entities, 列表中的第6点"当保存实体时,会发生一些事情" (" 6.父母协会得到保存")。所以我猜它解释了我所看到的。

1 个答案:

答案 0 :(得分:0)

我能想到这种情况:

  • 当您执行$ testTable-> save($ test)时,关联(测试)会与铭文相关联,因此在$ testTable->行($ test)后面调用$ inscriptions-> save( $测试)。在这种情况下,您可以尝试使用 - > update()而不是 - > save(),如saving data中所示,因为更新不会触发afterSave事件。