我正在学习cakephp,并且已经取得了很多成果。我问这个问题的唯一原因是 cakePHP 中的文档可能是错误的。 我无法从有关此问题的文档或过去的 stackoverflow 帖子中看出为什么(子)Teacher 表不保存(父)User 表中 id 表中的 user_id。 我没有收到错误,但教师表中的 user_id 为 0,因此它不会从用户表中获取它。 我对这两个模型有一对一的关系。 我只是测试保存超过 2 个模型,其中我有一个用户和老师。我只需在表单中输入数据并创建一个新用户和一个新教师,其中 user_id 是教师表中的外键。 我讨厌问这个问题,因为有很多关于这个问题的 Material ,但在遵循 cakePHP 中的文档后我只是看不到我的问题。
http://book.cakephp.org/2.0/en/models/saving-your-data.html
public function addteacher() {
if ($this->request->is('post')) {
$this->User->create();
}
if (!empty($this->request->data)) {
// We can save the User data:
// it should be in $this->request->data['User']
$user = $this->User->save($this->request->data);
// If the user was saved, Now we add this information to the data
// and save the Profile.
if (!empty($user)) {
// The ID of the newly created user has been set
// as $this->User->id.
$this->request->data['teacher']['user_id'] = $this->User->id; //here is the problem
// Because our User hasOne Profile, we can access
// the Profile model through the User model:
if ($this->User->Teacher->save($this->request->data))
{
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'login'));
}
}
}
}
<?php
echo $this->Form->create('User');
echo $this->Form->input('User.username');
echo $this->Form->input('User.password');
echo $this->Form->input('Teacher.firstname'); //text
echo $this->Form->input('Teacher.surname');
echo $this->Form->input('Teacher.address'); //text
echo $this->Form->input('Teacher.suburb');
echo $this->Form->input('Teacher.phone');
echo $this->Form->end('保存帖子'); ?>
最佳答案
$this->request->data['teacher']['user_id'] = $this->User->id;
应该是
$this->request->data['Teacher']['user_id'] = $this->User->id;
。
大写“T”。模型名称始终采用驼峰命名法。
也就是说,不需要进行 2 次保存。您只需使用
$this->User->saveAll($this->request->data);
。
它将保存用户记录和教师记录,并为教师记录添加适当的外键值(假设您已在用户和教师模型之间设置适当的关联)。
关于php - 无法在cakephp中保存多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23977849/