我有两个包含以下变量的表:
表1(用户): ID,fName,lName
表2(详情): table1ID,年龄,DOB
以下是我的表格:
<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')); ?>
我想在第一个表中插入 fname 和 lname ,然后重新获取ID并将ID,Age和DOB放入第二个表,只需按一次提交按钮。
* ID为自动增量
更新
这是我的模型
class User extends AppModel {
public $displayField = 'fName';
public $hasMany = array('Detail');
public $validate = array(
'fName' => 'notEmpty',
'lName' => 'notEmpty'
);
}
答案 0 :(得分:0)
<?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
答案 1 :(得分:0)
尝试这个简单的代码,它适合你。
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 :(得分:-1)
我不知道您使用的是哪个版本的蛋糕,但这里是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);