cakephp,如何在两个表中同时保存数据

时间:2014-02-08 07:53:50

标签: php mysql cakephp

我有两个表 - 用户和employee_personals。我想在插入employee_personal数据的同时将employee_personal.epf_no插入到users表中。我的代码如下所示

    if ($this->request->is('post')) 
    {
       $this->EmployeePersonal->create();
       $post_data = $this->request->data;
       if ($this->EmployeePersonal->save($post_data)) 
       {

          $data=$this->request->data['EmployeePersonal']['epf_no'];
          if ($this->User->save($data))
          {   
            $this->redirect(array('controller' =>'employee_personals','action'=>'add'));
          }

    }
$this->Session->setFlash(__('Unable to save personal details'));
}

当我提交表单时,会插入employee_personals,但user.epf_no为空。请帮助我编写函数

1 个答案:

答案 0 :(得分:0)

与其他答案/评论一样,最好使用saveAll()或saveAssociated()。但是,如果要继续执行代码,则需要更改$ data。以下应该有效:

$data['User']['epf_no'] = $this->request->data['EmployeePersonal']['epf_no'];
if ($this->User->save($data)) {...