我是 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
引用同一个表people
的primary_key people.id
。 role
的值可以是 manager
或 customer
。如果是 manager
,则 people.id
的值将分配给 people.parent_id
。
在我的注册表中,将有以下输入字段:
-username
-password
-first name
-last name
-street
-house no
-post code
-city
-role
在 View (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 中的操作:
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->saveAll($this->request->data)) {
$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.')
);
}
}
问题是前三个字段的数据(在用户和人员表中)被保存,其他数据(在地址表中)没有保存。
谁能告诉我我在这里错过了什么?
最佳答案
模型用户
与模型地址
没有直接关系。但是,它通过模型 Person
关联,其中 Person hasMany Address
。
尝试以下操作。
将您的 View 更改为:
$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
添加到 UsersController.add()
中的 saveAll()
:
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.')
);
}
}
关于mysql - CakePHP 2.5.1 中无法将数据从一个表单保存到多个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35010467/