Call other model's callback method

82 Views Asked by At

I'm using CakePHP 2.9. I want to call Child's afterSave in Parent's afterSave.

Here are my models with their callback methods :

Parent Model

/*
 * @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
        }
    }
}

Child Model

/*
 * @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
        }
    }
}

How can I call Child's afterSave in Parent's afterSave?

1

There are 1 best solutions below

1
flygaio On

Can you not do something like this:

class Parent extends AppModel {
    // ..

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