cakephp:如何通过saveAssociated保存hasmany链

时间:2015-03-07 10:06:45

标签: cakephp

基本上,有3种型号:

Class Model1 {
   Public $hasMany = array {
       'Model2' => array(
            'className' => 'Model2',
            'foreignKey' => 'model1id'
        )
   };
}

Class Model2 {
   Public $belongsTo = array {
       'Model1' => array(
            'className' => 'Model1',
            'foreignKey' => 'model1id'
        )
   };

   Public $hasMany = array {
       'Model3' => array(
            'className' => 'Model3',
            'foreignKey' => 'model2id'
        )
   };
}

Class Model3 {
   Public $belongsTo = array {
       'Model2' => array(
            'className' => 'Model2',
            'foreignKey' => 'model2id'
        )
   };
}

在Model1s视图文件夹下的ctp文件中,我的代码如下:

echo $this->Form->create('Model1');
echo $this->Form->input('[some_model1_field]');
echo $this->Form->input('Model2.0.[some_field]');
echo $this->Form->input('Model3.0.[some_field]');
echo $this->Form->end('Save');

在Controller中,具有如下功能:

$this->Model1->saveAssociated($this->request->data, array('deep' => true));

结果是所有字段都插入到db中,包括通过框架自动保存到model2表中的foreignkey model1id。唯一的问题是model2id无法通过框架自动保存到model3表中。怎么处理呢?

1 个答案:

答案 0 :(得分:0)

Model1Model3无关,但您的输入字段名称和生成的请求数据代表了这种关联。调试请求数据并将其与文档显示的内容进行比较

<强> http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array

结构的问题应该是显而易见的,它将类似于

[
    // ...
    'Model2' => [
        [/* ... */]
    ]
    'Model3' => [
        [/* ... */]
    ]
]

如果您想为Model3保存Model2,那么您必须正确嵌套数据

echo $this->Form->input('Model2.0.Model3.0.[some_field]');

应该会产生类似

的内容
[
    // ...
    'Model2' => [
        // ...
        'Model3' =>  [
            [/* ... */]
        ]
    ]
]