模型回调beforeDelete

时间:2010-07-16 11:38:45

标签: cakephp model callback

我在尝试使用级联模型删除这些图像的容器时删除图像:: delete

级联工作正常,但是我无法在删除后恢复模型,因此我可以在删除时删除实际的图像文件。

function beforeDelete() {
    $containerId = $this->id;
    $numberOfImages = $this->RelatedImage->find('count', array('conditions' => array('RelatedImage.container_id' => 'containerId')));
    if ($numberOfImages > 0){   
        $relatedImages = $this->RelatedImage->find('all', array('conditions' => array('RelatedImage.container_id' => 'containerId')));
        foreach ($relatedImages as $image) {
            $myFile = WWW_ROOT . 'image' . $containerId . '_i' . $image['RelatedImage']['id']  . '.jpg';
            unlink($myFile);
            $myThumb = WWW_ROOT . 'img/' . $image['RelatedImage']['thumbnail'];
            unlink($myThumb);
        }
        return true;
    } else{
        return false;
    }
}

if语句每次都失败,即使我知道表中有图像。如果我能得到if语句至少执行i,我将在unlink上添加进一步的验证。

2 个答案:

答案 0 :(得分:3)

我会这样做:

在beforeDelete中获取图像数据

function beforeDelete(){
  $relatedImages = $this->RelatedImage->find('all', array('conditions' => array('RelatedImage.container_id' => 'containerId')));
  $this->relatedImages = $relatedImages;
  $this->currentId = $this->id; //I am not sure if this is necessary
  return true;
}

然后在afterDelete()中,因为Oscar建议实际删除图像:

function afterDelete(){
  $relatedImages = $this->relatedImages;
  $containerId = $this->currentId; //probably this could be just $this->id;
  foreach ($relatedImages as $image) {
        $myFile = WWW_ROOT . 'image' . $containerId . '_i' . $image['RelatedImage']['id']  . '.jpg';
        unlink($myFile);
        $myThumb = WWW_ROOT . 'img/' . $image['RelatedImage']['thumbnail'];
        unlink($myThumb);
    }
}

这样你就可以保存,即使模型无法删除记录,只有删除实际发生时才会删除图像。

HTH

答案 1 :(得分:1)

如果模型与hasMany / hasOne相关,则删除它们时应调用RelatedImage :: beforeDelete()和RelatedImage :: afterDelete()。尝试将删除逻辑放在那里吗?