在使用级联模型删除那些图像的容器时,我试图删除图像::删除
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
发布评论