我需要在CakePHP 3.0的两个表中插入一个表单中的数据。
我知道我不能使用saveAll()
,因为已弃用。
这两个表格为Users
和Addresses
外键id(Users)
和user_id(Addresses)
在UsersTable
初始化中有$this->hasOne('Addresses');
和AddressesTable
$this->belongsTo('Users');
这是我的add.ctp:
<legend><?= __('Add User') ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role', [
'options' => ['admin' => 'Admin', 'chinateam' => 'China Team', 'italianteam' => 'Italian team', 'reseller'=>'Reseller']
]);
echo $this->Form->input('Address.address');
?>
UserController.php
public function add() {
$this->log('Quote Controller --> Add Method...1');
$this->log($this->request->data);
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data, ['associated' => ['Addresses']]);
if ($this->Users->save($user)) {
$this->Flash->success('The user has been saved.');
//return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
此脚本在Users
表中插入数据,但不在Addresses
表中插入。