将一个表单中的数据插入两个表中

时间:2015-04-14 05:21:41

标签: php cakephp cakephp-3.0

我需要在CakePHP 3.0的两个表中插入一个表单中的数据。

我知道我不能使用saveAll(),因为已弃用。 这两个表格为UsersAddresses

外键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表中插入。

0 个答案:

没有答案