2012-07-12 53 views
0

好的下午大家,我會直接指向這一點。我有這樣的代碼在我的模型:在zend模式中使用級聯刪除時運行函數

protected $_referenceMap = Array (
    "Imagens" => Array(
     "columns"  => Array (
      'paiId' 
     ), 
     "refTableClass" => "ModeloImagem", 
     "refColumns" => Array(
      "id" 
     ), 
     "onDelete" => self::CASCADE 
    ) 
); 

我要刪除這回事級聯被稱爲表中的圖像,所以我想知道是否有這樣的:

protected $_referenceMap = Array (
    "Imagens" => Array(
     "columns"  => Array (
      'paiId' 
     ), 
     "refTableClass" => "ModeloImagem", 
     "refColumns" => Array(
      "id" 
     ), 
     "onDelete" => function() { 
      foreach($image as $i) { 
       unlink($i); 
      } 
      return self::CASCADE 
     } 
    ) 
); 

回答

1

有是不是這樣的事情。你可以做的是擴展Zend_Db_Table的方法_cascadeDelete($parentTableClassname, array $primaryKey)來執行該功能。

這裏的一個這樣做的方法,雖然它是一個可怕的代碼重複量;你可能必須指定要傳遞給回調你自己的數據,或者修改根據您的回調或查詢是否失敗行爲:

class My_Db_Table extends Zend_Db_Table 
{ 
    const ON_DELETE_CALLBACK = 'onDeleteCallback'; 

    /** 
    * Called by parent table's class during delete() method. 
    * 
    * @param string $parentTableClassname 
    * @param array $primaryKey 
    * @return int Number of affected rows 
    */ 
    public function _cascadeDelete($parentTableClassname, array $primaryKey) 
    { 
     $rowsAffected = 0; 
     foreach ($this->_getReferenceMapNormalized() as $map) { 
      if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_DELETE])) { 
       switch ($map[self::ON_DELETE]) { 
        case self::CASCADE: 
         for ($i = 0; $i < count($map[self::COLUMNS]); ++$i) { 
          $col = $this->_db->foldCase($map[self::COLUMNS][$i]); 
          $refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]); 
          $type = $this->_metadata[$col]['DATA_TYPE']; 
          $where[] = $this->_db->quoteInto(
           $this->_db->quoteIdentifier($col, true) . ' = ?', 
           $primaryKey[$refCol], $type); 
         } 
         $this->_executeCallback($map, $where); 
         $rowsAffected += $this->delete($where); 
         break; 
        default: 
         // no action 
         break; 
       } 
      } 
     } 
     return $rowsAffected; 
    } 

    private function _executeCallback($map, $where) { 
     if (isset($map[self::ON_DELETE_CALLBACK]) && is_callable($map[self::ON_DELETE_CALLBACK])) { 
      call_user_func($map[self::ON_DELETE_CALLBACK], $where); 
     } 
    } 
} 

然後你用這種方法來定義的回調函數。儘管如此,你不能在回調函數中定義級聯。否則所有圖像每次都會被刪除Zend_Db_Table試圖找出是否從圖像表中刪除條目。

protected $_referenceMap = Array (
    "Images" => Array(
     "columns"  => Array (
      'paiId' 
     ), 
     "refTableClass" => "ModeloImagem", 
     "refColumns" => Array(
      "id" 
     ), 
     "onDelete" => self::CASCADE, 
     "onDeleteCallback" => function($where) { 
      // Determine which image to unlink 
      unlink($image); 
     } 
    ) 
);