无法将数据从CakePHP 2.5.1中的一个表单保存到多个表中

时间:2016-01-26 09:21:51

标签: mysql cakephp orm cakephp-2.x

我是CakePHP的新手,使用CakePHP 2.5.1和MySQL开发云应用程序。我有以下表格:

users

  id ,
  person_id(FK- people.id),
  username,
  password

people

  id, 
  parent_id(FK- people.id), 
  firsr_name,
  last_name,
  role

addresses

  address_id,
  person_id(FK- people.id),
  street,
  house no,
  post code,
  city

外键people.parent_id指的是同一个表primary_key people.id的{​​{1}}。 people的值可以是rolemanager。如果customer,则manager的值将分配给people.id

在我的注册表格中,会有以下输入字段:

people.parent_id

在视图(-username -password -first name -last name -street -house no -post code -city -role )中,我有以下字段:

view/Users/add.ctp

$options = array('manager' => 'Manager', 'customer' => 'Customer'); $attributes = array('legend' => false); echo $this->Form->radio('Person.role', $options, $attributes); echo $this->Form->input('User.username'); echo $this->Form->input('Person.last_name'); echo $this->Form->input('Person.first_name'); echo $this->Form->input('Address.street'); echo $this->Form->input('Address.house_no'); echo $this->Form->input('Address.post_code'); echo $this->Form->input('Address.city'); 中的操作:

UsersController

问题是保存前三个字段(用户和人员表)中的数据,不保存其他数据(地址表)。

有人能告诉我这里缺少什么吗?

1 个答案:

答案 0 :(得分:1)

模型User与模型Address没有直接关系。但是,它与模型Person相关,其中Person hasMany Address

请尝试以下操作。

将您的观点更改为:

    $options = array('manager' => 'Manager', 'customer' => 'Customer');
    $attributes = array('legend' => false);
    echo $this->Form->radio('Person.role', $options, $attributes);


    echo $this->Form->input('User.username');
    echo $this->Form->input('Person.last_name');
    echo $this->Form->input('Person.first_name');

    echo $this->Form->input('Person.Address.0.street');
    echo $this->Form->input('Person.Address.0.house_no');
    echo $this->Form->input('Person.Address.0.post_code');
    echo $this->Form->input('Person.Address.0.city');

并在'deep'=>true中将saveAll()添加到UsersController.add()

public function add() {
    if ($this->request->is('post')) {
        $this->User->create();
        if ($this->User->saveAll($this->request->data,['deep'=>true])) {
            $components = array('Session'); 
            $this->Session->setFlash('Welcome !');
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(
            __('The user could not be saved. Please, try again.')
        );
    }
}
相关问题