2010-07-16 45 views
1

我試圖刪除與級聯模式這些圖像的容器時刪除圖像::刪除型號回調beforeDelete

級聯工作正常,但我不能讓模型回調afterDelete正常工作所以我可以在刪除時刪除實際的圖像文件。

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語句,至少可以執行,我會在取消鏈接上添加更多驗證。

回答

3

我會做這樣:

在beforeDelete獲得的圖像數據

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()作爲奧斯卡建議做圖像的實際刪除:

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

1

如果模型與hasMany/hasOne相關,則在刪除RelatedImage :: beforeDelete()和RelatedImage :: afterDelete()時應該調用它們。嘗試把刪除邏輯呢?