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

时间:2011-04-18 22:57:22

标签: cakephp

如何添加项目并将其插入2个表格?​​

所以我有一个'Type'表和'SpecificType'表。

类型包含字段'id'和其他一些常用字段 SpecificType具有字段'id','type_id'和一些其他不常见的字段。

当我转到/ specific_types / add并提交时,理想情况下我想先将其添加到'Type',然后将其添加到'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时,第二个模型才会保存。

3 个答案:

答案 0 :(得分:1)

确保您的视图已设置为为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控制器正确设置了视图,表单中的所有数据都将存储在$this->data['SpecificType']中。如果您pr($this->data)并且需要在$this->data['SpecificType']之外保存数据,请查看并修复该视图。

旁注:您的设计听起来非常粗略。您永远不需要将数据保存在两个位置。我建议您重新访问应用程序的设计。如果你需要将相同的数据保存到两个表中,那么它有一些根本性的错误。

答案 1 :(得分:0)

只需将数据复制到数据数组中的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));
    }
}

答案 2 :(得分:0)

代码似乎没问题,请使用saveAll而不是save