从CakePHP中的一个表单连续插入两个表



我有两个表,其中包含以下变量:

表(用户):ID、帧lName

表二(细节):表id,年龄,年龄

这是我的Form in view:

<form action="/admin/users/add" id="WordAdminAddForm" method="post">
    <input type="text" name="data[text1][fName]" >
    <input type="text" name="data[text1][lName]" >
    <input type="text" name="data[text2][Age]" >
    <input type="text" name="data[text2][DOB]" >
<?php echo $this->Form->end(__('Add New User')); ?>

我想在第一个表中插入fnamelname,然后检索ID并将ID、Age和DOB放在第二个表中,只需按一次提交按钮。
* ID为Auto increment


这是我的模型

class User extends AppModel {
    public $displayField = 'fName';
    public $hasMany = array('Detail');
    public $validate = array(
        'fName' => 'notEmpty',
        'lName' => 'notEmpty'
    );
}
<?php
$data1 = $this->request->data['text1'];
$data2 = $this->request->data['text2'];
$profile= $this->Profiles->newEntity();
    if ($this->request->is('post')) {
        $profile = $this->Profiles->patchEntity($profile, $data1);
        if ($this->Profiles->save($data1)) {
            //get return id from first table
            $data2['tabelA_id'] = $profile->id;
            insert into 2nd table
            $profileChild = $this->ProfileChilds->newEntity();
            $profileChild = $this->ProfileChilds->patchEntity($profileChild, $data2);
        }
?>

或者可以在模型中定义关系hasOne。Cakephp将自动插入到第二个表中。http://book.cakephp.org/3.0/en/orm/associations.html

试试这个简单的代码,它可以为您工作。

       if(!empty($this->data))
       {
            $this->User->create();
            $fName= $this->data['text1']['fName'];
            $lName=$this->data['text1']['lName'];
            $data = array(
                    "fName"=>$fName,
                    "lName"=>$lName,
                );
            $list=$this->User->save($data);
            $this->Detail->create();
            $Age= $this->data['text2']['Age'];
            $DOB=$this->data['text2']['DOB'];
            $data_list= array(
                    "Age"=>$Age,
                    "DOB"=>$DOB,
                    "table1ID"=>$list['User']['ID'],
                );
            $this->Detail->save($data_list);
        }

我不知道你用的是哪个版本的蛋糕,但这是2.x

在控制器中,只需保存新用户,然后使用字段id保存详细信息

//save the user
$this->User->create();
$this->User->save($this->request->data['text1']);
//create the new details with the user id
$newDetail = $this->request->data['text2']);
$newDetail['table1ID'] = $this->User->id
//save the new details
$this->Detail->create();
$this->Detail->save($newDetail);

最新更新