本文介绍了模型回调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{
        return false;
    }
}

if语句每次都失败,在表中有图像。如果我可以得到if语句至少执行我将添加进一步验证unlink。

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.

推荐答案

这样:

在beforeDelete获取图像数据

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

然后在afterDelete()as Oscar建议做实际删除的图像:

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

这样即使保存模型,

HTH

这篇关于模型回调beforeDelete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 16:09