【问题标题】:Updating rows over 2 tables更新超过 2 个表的行
【发布时间】:2014-06-02 04:54:35
【问题描述】:

我在使用相关模型更新 2 个表时遇到问题。我可以自己编辑 1 个表格。我已经检查了文档和这里,但我还找不到这个简单的答案。

我得到的是一个新行,而不是一个编辑过的行。

文档说这是因为我没有不正确的 id 字段。 我可以摆弄并尝试让它工作,但我更喜欢传统方式,因为我需要使用saveAssociated?保存超过1个相关表的方法是什么?

User 表有一个 id 字段,Teacher 表有 user_id 外键。

现在,在我发帖之前,我检查了saveAllupdateAll 和其他帖子。

这1个型号是UserTeacher。一个UserhasOneTeacher和一个TeacherbelongsTo一个User

我不确定saveAllupdateAll 是否合适,因为它在文档中没有过多讨论编辑,而是添加了新内容。

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


    【解决方案1】:

    我倾向于将记录的id 存储为 URL 参数或表单中的隐藏字段。

     <?php
    
    
         echo $this->Form->create('User');
         // Added this next line
         echo $this->Form->hidden('User.id');
         echo $this->Form->input('User.username');   //text
         // Added this line too (if necessary)
         echo $this->Form->hidden('Teacher.id');
         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');
    
     ?>
    

    您需要包含您要更新的项目的记录id,否则会创建新记录。

    【讨论】:

    • 我尝试了 updateall 和 hidden 字段。我有一个新行或错误 user.user 不存在。更新全部只是将 this-request-data 作为数组?我仍然很抱歉
    • @ajt 如前所述,不要不要使用updateAll(),使用save()saveAssociated()。也许检查blog tutorial
    • 这是我原来的帖子,你是说回去?你没有提供任何选择,所以我一点也不聪明
    • 使用 savesaveAll 就像 ndm 说的那样
    • 如果您在我的原始帖子中查看我的代码,我确实使用 saveALL。但是我添加了隐藏字段,这很有效。这不在文档中,非常令人困惑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多