BeforeDelete model callback

I am trying to delete images when deleting the container of these images using the cascading model :: delete

Cascading works fine, but I can't get the model to return afterDelete to work correctly, so I can delete the actual image files when deleted.

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

The if statement fails every time, although I know there are images in the table. If I can get an if statement to at least execute, I will add an extra check for unlink.

+1
source share
2 answers

I would do it like this:

in beforeDelete get image 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 afterDelete (), since Oscar suggests doing the actual deletion 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);
    }
}

, , , .

+3

hasMany/hasOne, RelatedImage:: beforeDelete() RelatedImage:: afterDelete(), . ?

+1

All Articles