2013-12-23 72 views
1

我有一种形式可以保存具有许多零件和许多颜色的人,但不会保存零件和颜色;只保存该人(主要模型)。脚本的cakephp:使用一种形式保存到多个模型

在我的名单视图,部分:

echo $this->Form->input('Person.person_name', array('required' => true, 'placeholder' => 'Name Your Person', 'label' => false)); 
echo $this->Form->input('Part.0.part_name', array('required' => true, 'placeholder' => 'Add Part', 'label' => false)); 
echo $this->Form->input('Color.0.color_name', array('required' => true, 'placeholder' => 'Enter a Color', 'label' => false)); 

在我名单控制器:

if ($this->request->is('post')) { 
      $created = $this->Person->saveAll($this->request->data, array('validate'=>'first')); 
      if (!empty($created)) { 
       $this->Session->setFlash(__('The person and his/her parts and colors have been saved.')); 
       return $this->redirect(array('action' => 'index'));     
      } else { 
       $this->Session->setFlash(__('The person could not be saved. Please, try again.')); 
      } 
     } 

在我角色模型

public $hasMany = array(
    'PersonParts' => array(
     'className' => 'Part', 
     'foreignKey' => 'part_person_id' 
    ), 
    'PersonColors' => array(
     'className' => 'Color', 
     'foreignKey' => 'color_person_id' 
    ) 
); 

尝试用saveAssociated替换saveAll,但它是相同的。 我在这里做错了什么?任何帮助是极大的赞赏。

+0

你有三种型号对不对?并且值应该存储在不同的表中 –

+1

将模型别名保持为单独的PersonParts - PersonPart是一个好主意 - 否则应用程序的某些方面会令人困惑(例如需要包含名为PersonParts的表单字段) – AD7six

回答

2

必须(在hasMany变量别名等)在表单中添加别名原名:

echo $this->Form->input('Person.person_name'); 
echo $this->Form->input('PersonParts.0.part_name'); 
echo $this->Form->input('PersonColors.0.color_name'); 
+0

谢谢。天哪。不知道我必须这样做。这不是在cakephp文件呃? – Leah

1

更新您的形式

echo $this->Form->input('Part.part_name',...) 
echo $this->Form->input('Color.color_name',...) 

而在你的控制器,使用

**saveAssociated** 
+0

'SaveAll'在上下文中是'SaveAssociated'的别名。您提出的表单结构不适用于多关系。 – AD7six

0

我认为你需要独立保存的一切。

您对这种可能性有什么看法?

如果是,则通过。

$this->Person->Part->save(); 
$this->Person->Color->save(); 
1

试试这个

echo $this->Form->input('Person.person_name', array('required' => true, 'placeholder' => 'Name Your Person', 'label' => false)); 
echo $this->Form->input('PersonParts.0.part_name', array('required' => true, 'placeholder' => 'Add Part', 'label' => false)); 
echo $this->Form->input('PersonColors.0.color_name', array('required' => true, 'placeholder' => 'Enter a Color', 'label' => false)); 
0

为了节省您可以使用类似:

$this->Model->saveMany($data, array('deep'=>TRUE)); 

请注意,“深层”选项需要CakePHP 2.1。没有它,关联的评论记录将不会被保存。

所有这一切都在http://book.cakephp.org/2.0/en/models/saving-your-data.html

被证明也是正确的它

echo $this->Form->input('Person.person_name', array('required' => true, 'placeholder' => 'Name Your Person', 'label' => false)); 
echo $this->Form->input('Part.part_name', array('required' => true, 'placeholder' => 'Add Part', 'label' => false)); 
echo $this->Form->input('Color.color_name', array('required' => true, 'placeholder' => 'Enter a Color', 'label' => false)); 
+0

SaveMany用于保存相同类型的许多行__。这是问题的错误方法。 – AD7six