我创建了两个表第一个用户,第二个用户是user_datas,但数据只在user表中而不在user_datas表中
- >这是UsersController添加功能代码
公共功能add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data,['associated'=>'UserDatas']);
if ($this->Users->save($user)){
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
//$states = $this->Users->States->find('list', ['keyField'=>'id', 'valueField'=>'state_name','limit' => 200]);
$this->set(compact('user'));
$this->set('_serialize',['user']);
}
答案 0 :(得分:0)
首先,Users表和Userdatas表(hasOne或HasMany)之间的关系是什么。控制器代码:
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data,['associated'=>'UserDatas']);
if ($this->Users->save($user,['associated'=>'UserDatas'])){
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
//$states = $this->Users->States->find('list', ['keyField'=>'id', 'valueField'=>'state_name','limit' => 200]);
$this->set(compact('user'));
$this->set('_serialize',['user']);
如果用于收集数据的表单中的输入名称符合视图中的cakePHP表关系,则此方法将起作用。例如:
$this->Form->create($article);
// Article inputs.
echo $this->Form->input('title');
// Author inputs (belongsTo)
echo $this->Form->input('author.id');
echo $this->Form->input('author.first_name');
echo $this->Form->input('author.last_name');
// Author profile (belongsTo + hasOne)
echo $this->Form->input('author.profile.id');
echo $this->Form->input('author.profile.username');
// Tags inputs (belongsToMany)
echo $this->Form->input('tags.0.id');
echo $this->Form->input('tags.0.name');
echo $this->Form->input('tags.1.id');
echo $this->Form->input('tags.1.name');
// Multiple select element for belongsToMany
echo $this->Form->input('tags._ids', [
'type' => 'select',
'multiple' => true,
'options' => $tagList,
]);
// Inputs for the joint table (articles_tags)
echo $this->Form->input('tags.0._joinData.starred');
echo $this->Form->input('tags.1._joinData.starred');
// Comments inputs (hasMany)
echo $this->Form->input('comments.0.id');
echo $this->Form->input('comments.0.comment');