Cakephp After delete all

1.6k Views Asked by At

Why does cakephp have not any callback for after saveAll and deleteAll like beforeSave() and beforeDelete()? I know cakephp uses foreach for deleteAll() and saveAll which uses default delete() and save() function. But doesn't it uses too much queries, if i'm set any function like afterSave(), beforeSave() as it will execute every time whenever save() function will be execute.

Doesn't cakephp require separate function for saveAll(), deleteAll()? Correct me if i'm wrong.

1

There are 1 best solutions below

0
On BEST ANSWER

As you already said yourself, saveAll and deleteAll are basically just wrappers around save() and delete(). Therefor it will trigger beforeSave() and beforeDelete() for each row of data is saves or deletes. So adding a separate beforeSaveAll and beforeDeleteAll isn't really necessary. Yes, it could run a lot of queries, but that doesn't have to be a problem. It does offer a way to mould every row of data that is saved or deleted rather than doing one single bulk operation that can either work or fail entirely (because they're all dependent of each other when you bundle them into one operation).

If you would want to add any custom logic to every saveAll and deleteAll action (be very sure that is what you actually want! And remember that the regular beforeSave and beforeDelete will still be called unless you disable the callbacks in each saveAll and deleteAll), you can simply overwrite the methods with your own implentation in your AppModel and have it call your custom "before" logic, like:

// Add your own custom deleteAll and saveAll to AppModel
public function deleteAll($conditions, $cascade = true, $callbacks = false) {
    if ($this->beforeDeleteAll($conditions)) {
        parent::deleteAll($conditions, $cascade, $callbacks);
    } else {
        return false;
    }
}

public function saveAll($data = array(), $options = array()) {
    if ($this->beforeSaveAll($data, $options)) {
        parent::saveAll($data, $options);
    } else {
        return false;
    }
}

// As well as your custom logic
public function beforeDeleteAll($conditions) {
    // Do your stuff here
    return true;
}

public function beforeSaveAll($data, $options) {
    // Do your stuff here
    return true;
}