2011-01-10 48 views
0

我想要連接表自動更新/刪除。我在saveAll()之前做了一個deleteAll()作爲解決方法。CakePHP saveAll()不會刪除或更新連接表

當我提交表單時,佈局和組件模型正確更新,但佈局組件模型(它是連接表)插入新數據(這是我想要的),但不刪除引用的數據。

佈局模型:

class Layout extends AppModel { 
    var $name = 'Layout'; 

    var $hasMany = array(
     'LayoutComponentOrder' => array(
      'className' => 'LayoutComponentOrder', 
      'foreignKey' => 'layout_id', 
      'dependent' => false, 
      'order' => 'LayoutComponentOrder.sort_id ASC', 
     ), 
     'ComponentVideo' => array(
      'className' => 'ComponentVideo', 
      'foreignKey' => 'layout_id', 
      'dependent' => false, 
     ), 
);} 

組件模型:

class ComponentVideo extends AppModel { 
    var $name = 'ComponentVideo'; 
    //The Associations below have been created with all possible keys, those that are not needed can be removed 

    var $hasMany = array(
     'LayoutComponentOrder' => array(
      'className' => 'LayoutComponentOrder', 
      'foreignKey' => 'layout_component_id', 
      'dependent' => false, 
     ), 
    ); 

    var $belongsTo = array(
     'Layout' => array(
      'className' => 'Layout', 
      'foreignKey' => 'layout_id' 
     ), 
    ); 
}; 

佈局組件模型(合併表):

class LayoutComponentOrder extends AppModel { 
    var $name = 'LayoutComponentOrder'; 
    var $uses = 'layout_component_orders'; 

    //The Associations below have been created with all possible keys, those that are not needed can be removed 

    var $belongsTo = array(
      'Layout' => array(
       'className' => 'Layout', 
       'foreignKey' => 'layout_id' 
      ), 
      'ComponentVideo' => array(
       'className' => 'ComponentVideo', 
       'foreignKey' => 'layout_component_id' 
      ) 
     ); 
} 

佈局控制器:

// deleting the data manually 
$this->LayoutComponentOrder->deleteAll(array('LayoutComponentOrder.layout_id' => $layout_id)); 
// this one inserts into the tables including the join table   
$this->Layout->id = $layout_id; 
if ($this->Layout->saveAll($this->data)) { 
    $this->Session->setFlash(__('The layout has been saved', true)); 
} 

如何自動刪除連接?這可能與CakePHP?

回答

1

不幸的是,這並沒有嵌入到CakePHP的saveAll for hasany關係中。我希望它是,因爲我發現這個頁面尋找同樣的東西的解決方案。不過,它看起來與HABTM關係一樣。

參見Is there a way to make saveAll() remove extraneous objects?Shouldn't saveAll remove associated records as well?)

你必須實現你自己的解決方案(我的快速解決方案在saveAll之前運行一個deleteAll,如果表單驗證的話,這並不理想,因爲如果有一個與表單驗證無關的錯誤,相關項目)。

0

也許我不明白這個問題,但是當我們從Cake中刪除父記錄時,我們是否會討論刪除連接?它不這樣做,如果配置模型關係用「依賴」參數:

相關:當依賴鍵設置爲true,該模型的 刪除()方法被調用級聯參數組爲真, 關聯的模型記錄也被刪除。在這種情況下,我們將其設置爲 爲真,以便刪除用戶也將刪除她關聯的配置文件。

http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html

這就是你想要的?