调用其他模型的回调方法

时间:2017-07-24 06:00:22

标签: php cakephp cakephp-2.9

我正在使用CakePHP 2.9。我想在Parent afterSave中调用Child 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

1 个答案:

答案 0 :(得分:0)

你能不能做这样的事情:

class Parent extends AppModel {
    // ..

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