在CakePHP 2中编辑表:更新/插入错误


Edit table in CakePHP 2: Update/Insert error

问题:编辑条目时,SQL执行INSERT而不是UPDATE。

我有两个SQL表:users和users_tail。CCD_ 1&users_detail(id,adress,city,user_id)

外键users_detail.user_id被链接到users.id

例如,如果用户想编辑他的地址,我在cakepp应用程序中有一个表单可以编辑users_detail。这是我的控制器:

        public function admin_edit_dashboard($id = null){
    if (!$this->User->exists($id)) {
        throw new NotFoundException('Invalid user details');
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        if ($this->User->UserDetail->save($this->request->data, true, ['id', 'address', 'city'])) {
            $this->Session->setFlash('The user has been saved');
            return $this->redirect(array('action' => 'dashboard'));
        } else {
            $this->Session->setFlash('The user could not be saved. Please, try again.');
        }
    } else {
        //$this->request->data = $this->User->read(null, $id);
        $user = $this->User->UserDetail->find('first', array(
            'conditions' => array(
                'UserDetail.user_id' => $id
            )
        ));
        $this->request->data = $user;
    }
    $this->set(compact('user'));
}

我的表格:

<?php echo $this->Form->create('UserDetail');?>
        <?php echo $this->Form->input('address', array('class' => 'form-control')); ?>
        <br />
        <?php echo $this->Form->input('city', array('class' => 'form-control')); ?>
        <br />
        <?php echo $this->Form->button('Submit', array('class' => 'btn btn-primary')); ?>
        <?php echo $this->Form->end(); ?>

但当我验证表格以编辑详细信息时,我出现了一个错误:

错误:SQLSTATE[23000]:完整性约束冲突:1062键"PRIMARY"的重复条目"0"

因为SQL查询不是UPDATE,而是INSERT。我不知道为什么。

SQL查询:INSERT INTO cakeuser_detailsadress_ex,伦敦)

谢谢!

编辑:很管用,谢谢你的帮助!添加了良好的代码

您似乎有几个问题。

$this->request->address正确。表单数据以users(id,role,name,password)0的形式传递,因此您应该使用$this->request->data['UserDetail']['address']

如果你想确保你只保存特定的字段,你可以把它们作为save()的第三个参数传递,然后你不需要事先使用set():-

$this->UserDetail->save($this->request->data, true, ['id', 'address', 'city']);

SQL错误意味着user_details表上的主键没有设置为自动递增(应该是自动递增)。这就是INSERT失败的原因。

你还忘记了传递你试图更新的记录的主键,所以Cake假设你想创建一个新记录。请确保包含此内容,以便Cake知道使用UPDATE。例如,在您的视图表单中包括以下内容:-

echo $this->Form->hidden('id');

您的User模型应该与UserDetail有关联,如:

public $hasOne = array('UserDetail');

和你在UserDetail:

public $belongsTo = array('User');

那么你不必使用loadModel,只需使用:

$this->User->UserDetail->find('first', array(...));

您应该编辑UserDetailsController操作中的用户详细信息。

在您的视图中添加行以了解您正在编辑的内容:

echo $this->Form->input('id');

然后用传递的$this->request->data进行保存。这样就可以了。就像我说的,检查数据库中的表id,它必须是自动递增的。

您不能通过告诉控制器来更新您的表

$this->UserDetail->save($this->request->data)

相反,你应该尝试做一些类似的事情

//find that specific row in database and then update columns and save it
$this->UserDetail->set(array('address'=>$request->address,'city'=>$request->city));                
$this->UserDetail->save();

您的模型希望将其保存为id = 0下的新user_details,因为您没有指定要更新它以及要更新哪些列,所以CCD_24已经存在。

希望它能帮助