创建具有嵌套关联的表单

时间:2013-07-19 03:27:00

标签: cakephp

假设我有一个模型A,B和C:

class A extends AppModel {
    public $hasOne = array(
        'B1' => array(
            'className' => 'B',
            ...
        ),
        'B2' => array(
            'className' => 'B',
            ...
        )
    );

    ...
}

class B extends AppModel {
    public $belongsTo = 'A';

    public $hasOne = array(
        'C' => array(
            'className' => 'C',
            ...
        )
    );

    ...
}

class C extends AppModel {
    public $belongsTo = 'B';
}

我想允许用户编辑A的实例/行的字段以及A.B1,A.B2,A.B1.C和A.B2.C的相关实例/行。我知道我可以做到

echo $this->Form->create('A');
echo $this->Form->input('A.some_field');

echo $this->Form->input('B1.some_field');
echo $this->Form->input('B2.some_field');
...

echo $this->Form->submit();
echo $this->Form->end();

并使用saveAll保存请求,但如何引用A.B1.C和A.B2.C中的字段?我尝试了B1.C.some_field和B2.C.some_field但是没有用。

1 个答案:

答案 0 :(得分:2)

取决于您正在使用的Cake版本

从2.1 saveAll saves unlimited levels deep开始,答案与your last question相同/相似:

echo $this->Form->create('A');
echo $this->Form->input('A.id');

echo $this->Form->input('B.0.some_field');
echo $this->Form->input('B.0.C.name');
echo $this->Form->input('B.1.some_field');
echo $this->Form->input('B.0.C.name');
...

echo $this->Form->submit();
echo $this->Form->end();

如果使用deep option,那将以与saveAll相同的格式生成数据:

function edit($id) {
    ...
    $success = $this->A->saveAll($data, array('deep' => true));
}