模型回调 beforeDelete [英] Model Callback beforeDelete

查看:14
本文介绍了模型回调 beforeDelete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用级联模型删除那些图像的容器时,我试图删除图像::删除

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

级联工作正常,但我无法让模型回调 afterDelete 正常工作,因此我可以在删除时删除实际的图像文件.

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 语句至少执行,我将在取消链接上添加进一步的验证.

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() 中执行图像的实际删除:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆