CakePHP更新关联数据

时间:2014-06-23 09:47:19

标签: cakephp cakephp-2.3

在我的项目中,我有两个相关的模型:CompanyCompanyComment。公司有一个公司评论。

现在,当我想通过saveAssociated更新公司的信息时,我会按以下方式进行:

控制器操作:

    public function edit($id = null){

        $this->Company->id=$id;

        $this->Company->recursive = 0;      

        if($this->request->is('post')|| $this->request->is('put')){


            if($this->Company->saveAssociated($this->request->data)){
                $this->Session->setFlash(__('data has been updated'), 'positive_notification');
                $this->redirect(array('controller'=>'companies', 'action'=>'overview'));
            } else{
                $this->Session->setFlash(__('Data has not been updated. '), 'negative_notification');
            }
            }else{
            $this->request->data = $this->Company->read();
            }

    }

观点如下:

<?php echo $this->Form->create('Company', array('enctype' => 'multipart/form-data'));?>

<fieldset>

    <?php
        echo $this->Form->input('Company.newsletter');
        echo $this->Form->input('CompanyComment.comment_1', array('label'=>__('Domas comment'))); 
        echo $this->Form->input('CompanyComment.comment_2', array('label'=>__('Sunny comment')));
        ?>


    </fieldset>
<?php echo $this->Form->end(__('Update'));?>

以下是保存前的请求数据:

array(
    'Company' => array(
        'newsletter' => '1'
    ),
    'CompanyComment' => array(
        'comment_1' => 'comment1',
        'comment_2' => 'comment2'
    )
)

但它不会保存数据。非常感谢任何帮助或指导。

以下是公司模型关系:

var $hasOne = 'CompanyComment';

再说一遍,CompanyComment表的主键是company_id,而不是自动增加的id。

2 个答案:

答案 0 :(得分:0)

试试这个

public function edit($id = null){

    $this->Company->id=$id;

    $this->Company->recursive = 0;     <--Remove this line

    if($this->request->is('post')|| $this->request->is('put')){

 //Change here saveAssociated to saveAll like following
        if($this->Company->saveAll($this->request->data)){
            $this->Session->setFlash(__('data has been updated'), 'positive_notification');
            $this->redirect(array('controller'=>'companies', 'action'=>'overview'));
        } else{
            $this->Session->setFlash(__('Data has not been updated. '), 'negative_notification');
        }
        }else{
        $this->request->data = $this->Company->read();
        }

}

答案 1 :(得分:0)

你说:

  

再说一遍,CompanyComment表的主键是company_id,而不是自动增加的id。

你有没有在你的模特上改变它?

http://book.cakephp.org/2.0/en/models/model-attributes.html

class CompanyComment extends AppModel {
    public $primaryKey = 'company_id';
}