CakePHP-将项目添加到2个模型中

|| 如何添加项目并将其插入2个表中? 所以我有一个\'Type \'表和\'SpecificType \'表。 类型具有字段“ id”和其他一些常见字段。 SpecificType具有字段\'id \',\'type_id \'和其他一些不常见的字段。 当我转到/ specific_types / add并提交时,理想情况下,我想先将其添加到\'Type \',然后将其添加到\'SpecificType \'。 这就是我现在所拥有的。 在SpecificType模型中
var $belongsTo = array(
    \'Type\' => array(
        \'className\' => \'Type\',
        \'foreignKey\' => \'type_id\',
        \'conditions\' => \'\',
        \'fields\' => \'\',
        \'order\' => \'\'
    )
);
在SpecificType控制器中
var $uses = (\'Type\', \'SpecificType\');

function add() {
    if (!empty($this->data)) {
        $this->Type->create();
        if ($this->Type->save($this->data)) {
            $this->SpecificType->create();
            if ($this->SpecificType->save($this->data)) {
                $this->Session->setFlash(__(\'The SpecificType has been saved\', true));
                $this->redirect(array(\'action\' => \'index\'));
            } else {
                $this->Session->setFlash(__(\'The SpecificType could not be saved. Please, try again.\', true));
            }
        } else {
            $this->Session->setFlash(__(\'The Type could not be saved. Please, try again.\', true));
        }
    }
}
在SpecificType add.ctp
echo $form->input(\'Type.data1\');
echo $form->input(\'title\');
因此,现在,它保存Type.data1,但标题未保存。 我想念什么? 谢谢, 三通 附加信息: 仅当我打开MeioUpload时,第二个模型不会保存。
已邀请:
确保您的视图已设置为SpecificType创建表单:
<?php echo $this->Form->create(\'SpecificType\', array(\'action\' => \'add\')); ?>
<?php echo $this->Form->input(\'data1\'); ?>
<?php echo $this->Form->input(\'title\'); ?>
<?php echo $this->Form->end(); ?>
这会将您所有的表单数据放入:
$this->data[\'SpecificType\']
在您的代码之前:
$this->Type->create();
您需要这样做:
$this->data[\'Type\'] = $this->date[\'SpecificType\'];
然后进行保存。只要正确地为SpecificType控制器设置了视图,表单中的所有数据都将存储在“ 4”中。如果您使用
pr($this->data)
,并且您需要保存除
$this->data[\'SpecificType\']
之外的数据,请查看并修复视图。 旁注:您的设计听起来非常粗略。您永远不需要将数据保存在两个位置。我建议您重新设计应用程序的设计。如果您需要将相同的数据保存到两个表中,则从根本上来说是有问题的。
只需将数据复制到数据数组中的SpecificType索引中,然后使用saveAll()。这些模型是相关的,因此Cake将通过type_id自动链接它们。我们正在处理Type别名,因此请确保您的Type模型中也有
var $hasMany = array(\'SpecificType\');
function add() {
    if (!empty($this->data)) {
        $this->Type->create();
        $this->data[\'SpecificType\'] = $this->data;
        if ($this->Type->saveAll($this->data)) {
            $this->Session->setFlash(__(\'The SpecificType has been saved\', true));
            $this->redirect(array(\'action\' => \'index\'));
        } else {
            $this->Session->setFlash(__(\'The SpecificType could not be saved. Please, try again.\', true));
        }
    } else {
        $this->Session->setFlash(__(\'The Type could not be saved. Please, try again.\', true));
    }
}
该代码似乎很好,使用saveAll而不是save

要回复问题请先登录注册