CakePHP saveAll()不会删除或更新连接表

时间:2011-01-10 19:51:32

标签: cakephp model-associations

我希望自动更新/删除联接表。我在saveAll()之前做了一个deleteAll()作为解决方法来执行此操作。

当我提交表单时,布局和组件模型正确更新,但布局组件模型(连接表)插入新数据(这是我想要的)但不删除引用的数据。

布局模型:

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可以实现吗?

2 个答案:

答案 0 :(得分:1)

不幸的是,这并没有内置到CakePHP的saveAll for hasMany关系中。我希望是这样,因为我发现这个页面正在寻找同样的解决方案。

但它似乎与HABTM关系一起构建。

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

你必须实现自己的解决方案(如果表单验证,我在saveAll之前运行deleteAll的快速​​解决方案。但这并不理想,因为如果存在与表单验证无关的错误,则会丢失现有关联项目)。

答案 1 :(得分:0)

也许我不理解这个问题,但我们是否在谈论从Cake中删除父记录时删除联接?如果使用'dependent'参数在模型关系中进行配置,它确实会这样做:

  

dependent:当依赖键设置为true时,模型为   在cascade参数设置为true的情况下调用delete()方法,   相关的模型记录也被删除。在这种情况下,我们设置它   为了删除用户也会删除她关联的个人资料。

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

这就是你要找的东西吗?