【发布时间】:2014-06-02 04:54:35
【问题描述】:
我在使用相关模型更新 2 个表时遇到问题。我可以自己编辑 1 个表格。我已经检查了文档和这里,但我还找不到这个简单的答案。
我得到的是一个新行,而不是一个编辑过的行。
文档说这是因为我没有不正确的 id 字段。
我可以摆弄并尝试让它工作,但我更喜欢传统方式,因为我需要使用saveAssociated?保存超过1个相关表的方法是什么?
User 表有一个 id 字段,Teacher 表有 user_id 外键。
现在,在我发帖之前,我检查了saveAll、updateAll 和其他帖子。
这1个型号是User和Teacher。一个UserhasOneTeacher和一个TeacherbelongsTo一个User。
我不确定saveAll 或updateAll 是否合适,因为它在文档中没有过多讨论编辑,而是添加了新内容。
http://book.cakephp.org/2.0/en/models/saving-your-data.html
CakePHP - Updating multiple tables at the same time
查看代码
<?php
echo $this->Form->create('User');
echo $this->Form->input('User.username'); //text
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('Save Post');
?>
控制器代码
<?php
public function editteacher($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->User->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->User->id = $id;
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('Your techer has been updated.'));
return $this->redirect(array('controller' => 'teachers', 'action' => 'displayall'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
?>
【问题讨论】:
标签: php cakephp cakephp-2.0