使用cakephp保存数据不起作用

vit*_*tto 0 error-handling save cakephp-2.0

我想load,editsave用一记CakePHP 2.0,但我得到generic error 的期间save不帮我明白问题出在哪里方法.

如果我尝试debug($this->User->invalidFields());我得到一个empty array,但我false$this->User->save()条件得到.

这是我得到错误的控制器操作:

public function activate ($code = false) {
    if (!empty ($code)) {

        // if I printr $user I get the right user
        $user = $this->User->find('first', array('activation_key' => $code));

        if (!empty($user)) {
            $this->User->set(array (
                'activation_key' => null,
                'active' => 1
            ));

            if ($this->User->save()) {
                $this->render('activation_successful');
            } else {
                // I get this error
                $this->set('status', 'Save error message');
                $this->set('user_data', $user);
                $this->render('activation_fail');
            }
            debug($this->User->invalidFields());

        } else {
            $this->set('status', 'Account not found for this key');
            $this->render('activation_fail');
        }
    } else {
        $this->set('status', 'Empty key');
        $this->render('activation_fail');
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试动作时,test.com/users/activate/hashedkey我得到activation_fail带有Save error message消息的模板页面.

如果我printr$uservar我从cake的find方法中获得了正确的用户.

哪里我错了?

bri*_*ism 5

我认为问题可能在于您查询用户记录的方式.当你这样做:

$user = $this->User->find('first', array('activation_key' => $code));
Run Code Online (Sandbox Code Playgroud)

该变量$user将用户记录填充为数组.你检查确保它不是空的,然后继续; 问题是$this->User尚未填充.我想如果你试过debug($this->User->id)它会是空的.在read()方法的工作你想的方式.

您可以尝试使用该$user数组中的ID首先设置Model ID,如下所示:

if (!empty($user)) {
    $this->User->id = $user['User']['id']; // ensure the Model has the ID to use
    $this->User->set(array (
        'activation_key' => null,
        'active' => 1
    ));
    if ($this->User->save()) {
    ...
Run Code Online (Sandbox Code Playgroud)

编辑:另一种可能的方法是使用$user数组而不是修改当前模型.你曾经说过,如果你有回复有效的用户debug($user),那么如果这是真的,你可以这样做:

if (!empty($user)) {
    $user['User']['activation_key'] = null;
    $user['User']['active'] = 1;
    if ($this->User->save($user)) {
    ...
Run Code Online (Sandbox Code Playgroud)

此方法的工作方式与从表单中接收表单数据的方式相同$this->request->data,并在本书的" 保存数据"部分中进行了描述.

我很好奇,如果你的设置的另一部分正在阻碍.您应用的其他部分可以正确写入数据库吗?您还应检查以确保没有验证错误,例如:

<?php
if ($this->Recipe->save($this->request->data)) {
    // handle the success.
}
debug($this->Recipe->validationErrors);
Run Code Online (Sandbox Code Playgroud)