开发者

Model Callback beforeDelete

I'm trying to delete images when deleting the container of those images with a cascading model::delete

The cascading works fine, but I can't get the model call back afterDelete to work properly so I can delete the actual image files when doing the 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{
        开发者_JAVA技巧return false;
    }
}

The if statement fails each time, even though I know there are images in the table. If I can get the if statement to at least execute i will add further validation on the unlink.


I would do it in this way:

in beforeDelete get the images data

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;
}

then in the afterDelete() as Oscar suggest do the actual delete of the image:

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);
    }
}

this way you are save, even if the model fail to delete the record you will delete images only if the delete was actually happen.

HTH


If the models are related with hasMany/hasOne, both RelatedImage::beforeDelete() and RelatedImage::afterDelete() should be called when they are removed. Try putting the delete logic there instead?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜