2011-01-10 47 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

这就是你想要的?