2

我有一种表格可以保存一个人的许多零件和许多颜色,但它没有保存零件和颜色;只救人(主要模型)。

在我的列表视图中,脚本的一部分:

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 但它是一样的。我在这里做错了什么?任何帮助是极大的赞赏。

4

5 回答 5

3

您必须在表单中添加别名的原始名称(hasMany变量中的别名):

echo $this->Form->input('Person.person_name');
echo $this->Form->input('PersonParts.0.part_name'); 
echo $this->Form->input('PersonColors.0.color_name');
于 2013-12-23T10:33:18.697 回答
1

将您的表格更新为

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

在您的控制器中,使用

**saveAssociated**
于 2013-12-23T10:25:15.920 回答
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) );
于 2013-12-23T10:29:12.693 回答
0

我认为您需要独立保存所有内容。

您如何看待这种可能性?

如果是,则通过。

$this->Person->Part->save();
$this->Person->Color->save();
于 2013-12-23T10:29:00.380 回答
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) ); 
于 2013-12-23T10:33:32.733 回答