CakePHP模型回调,特别是在删除之前

wco*_*ert 2 cakephp models

我想在删除字段之前执行一些逻辑.我有一些模型依赖于被删除的模型,我想确保与这些相关模型相关的图像文件也被删除,但我对模型回调如何工作有点困惑.

我知道我在模型类中定义了之前的Delete函数,但是如何访问当前模型中的数据或被删除的依赖模型?

function beforeDelete() {

}
Run Code Online (Sandbox Code Playgroud)

我对如何使用这些回调感到有点困惑,我还没有看到任何好的文档.

编辑: 将此添加到父模型后,它似乎总是返回false.

function beforeDelete() {
    if ($this->DependentModel->find('count', array('conditions' => array('DependentModel.parent_id' => $this->id))) == 1){  
        return true;
    } else{
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

应该是显而易见的我在这里要做的事情.如果表中存在依赖模型的一个条目,则返回true并继续删除.我确保实际上有一个表条目依赖于被删除的对象.当我执行删除操作时,它总是返回false.这里发生了什么?

dei*_*zel 9

使用回调时,您可以参考要扩展的类的API以检查它接受的参数.您的实现应至少接受与您覆盖的方法相同的参数.

例如,Model::beforeDelete实现如下:

/**
 * Called before every deletion operation.
 *
 * @param boolean $cascade If true records that depend on this record will also be deleted
 * @return boolean True if the operation should continue, false if it should abort
 * @link http://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete
 */
    public function beforeDelete($cascade = true) {
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

并且,这样ModelBehavior::beforeDelete实现(即,在进行行为时):

/**
 * Before delete is called before any delete occurs on the attached model, but after the model's
 * beforeDelete is called.  Returning false from a beforeDelete will abort the delete.
 *
 * @param Model $model Model using this behavior
 * @param boolean $cascade If true records that depend on this record will also be deleted
 * @return mixed False if the operation should abort. Any other result will continue.
 */
    public function beforeDelete(Model $model, $cascade = true) {
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

接下来,知道保存到模型并传入控制器的数据(即$this->data在控制器中)将数据设置为模型(即$this->data模型中)时,这很有用.[发生在这期间Model::save(),目前在1225行.]

在第一个示例的情况下,您可以使用$this和在第二个示例中访问模​​型,您可以使用$model($this在该上下文中的行为)访问模型.因此,要获取数据,您要使用$this->data$model->data.您还可以使用链接(即.$this->RelatedModel$model->RelatedModel)访问该模型的相关模型.

作为docblock注释状态,$cascade如果true您的代码需要采取不同的操作(如果是或不是这种情况),应该让您知道这是否是正在发生的级联删除(默认情况下); 如果要中止保存操作,则该方法的实现应返回false(否则,在完成后返回true).

CakePHP 有一个Media插件,它实现了可用作参考的确切功能.