【问题标题】:Call other model's callback method调用其他模型的回调方法
【发布时间】:2017-07-24 06:00:22
【问题描述】:

我正在使用 CakePHP 2.9。我想在父母的afterSave 中打电话给孩子的afterSave

这是我的模型及其回调方法:

父模型

/*
 * @property Child @Child
 */

class Parent extends AppModel {
    public $hasMany = [
        'Child' => array(
            'className' => 'Child',
            'foreignKey' => 'parent_id',
            'dependent' => false,
            )
    ];

    public function afterSave($created, $options = array()){
        if( ! $created && $this->data['Parent']['status'] == 0 ) {
            // Update child's status
        }
    }
}

儿童模型

/*
 * @property Grandchild @Grandchild
 */
class Child extends AppModel {
    // belongs to Parent

    public $hasMany = [
        'Grandchild' => array(
            'className' => 'Grandchild',
            'foreignKey' => 'child_id',
            'dependent' => false,
            )
    ];

    public function afterSave($created, $options = array()){
        if( ! $created && $this->data['Child']['status'] == 0 ) {
            // Update grandchild's status
        }
    }
}

如何在父母的afterSave 中调用孩子的afterSave

【问题讨论】:

  • 在父类afterSave方法中创建子类的对象,然后使用创建的对象调用子类afterSave方法
  • @RAUSHANKUMAR 你好,Raushan,它不工作。回调方法没有被调用。
  • 保存后你在哪里调用它?首先,您需要检查方法是否被调用。在 afterSave() 上打印一些东西;
  • 嗨@KevinKyaw, afterSave 方法在每个模型的事件中被调用(已经检查)。但是如果我做一些事情来触发Parent的afterSave,那么Child的afterSave就不会被触发。
  • 意思是,如果你在 Parent 的 aftersave 中做点什么,它就起作用了。但是,孩子的事后储蓄不起作用对吗?换一种方式,如果你在 Child 的 aftersave 上做某事,Parent 的 aftersave 是否有效?

标签: php cakephp cakephp-2.9


【解决方案1】:

你不能这样做吗:

class Parent extends AppModel {
    // ..

    public function afterSave($created, $options = array()){
        if(!$created && $this->data['Parent']['status'] == 0) {
            $child = new Child();
            $child->afterSave($created, $options);
        }
    }
}

【讨论】:

  • 嗨@flygaio,如果我按照您的建议进行操作,$this->data['Child']['status'] 只是 Child's Model 中的一个空数组。如何将数据发送到 Child's Model?关系是:父母有很多孩子,孩子有很多孙子。
猜你喜欢
  • 2018-04-29
  • 2014-12-14
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
  • 2017-09-26
  • 2015-01-22
相关资源
最近更新 更多