模型回调 beforeDelete

编程入门 行业动态 更新时间:2024-10-25 19:26:16
本文介绍了模型回调 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

本文发布于:2023-08-01 09:14:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267169.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   模型   beforeDelete

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!