dongmei8209 2013-12-23 10:19
浏览 27
已采纳

cakephp:使用一个表单保存到多个模型

I have one form that saves a person with many parts and many colors but it's not saving the parts and the colors; only saving the person(main model).

On my list view, part of script:

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) ); 

On my list controller:

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.'));
            }
        }

On my Person Model:

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

Tried replacing saveAll with saveAssociated but it's the same. What am I doing wrong here? Any help is greatly appreciated.

  • 写回答

5条回答 默认 最新

  • duandiaoqian5795 2013-12-23 10:33
    关注

    You must add original name of alias in form (alias like in hasMany variable):

    echo $this->Form->input('Person.person_name');
    echo $this->Form->input('PersonParts.0.part_name'); 
    echo $this->Form->input('PersonColors.0.color_name');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?