在cakephp中更新的问题

时间:2011-01-07 15:09:04

标签: cakephp

您好,我正在尝试更新已保存在数据库表中的userdata,但有些我是如何创建新记录而不是更新现有记录。这是我的代码。

function admin()
{       
    $conditions = "id";
    $recursive = 1;
    $data = $this->User->find('all');
    $counter = $this->User->find('count');
    $this->set('counter', $counter);
    $this->set('combo', $data);

    $username = $this->Session->read('user');
    if ($username)
    {
        $results = $this->User->findByUsername($username);
        $this->set('User', $results['User']);
        $this->set('last_login', $this->Session->read('last_login'));
        if (!empty($this->data))
        {


            $this->data["User"]["access_right"] = implode(",",$this->data["User"]["access_right"]);
            $this->User->set($this->data);
            if ($this->User->validates())
            {                    
               $this->data['User']['password'] = md5($this->data['User']['password']);
               if($this->User->saveAll($this->data, TRUE, array('username','password','first_name','last_name','notes','access_right')))
               {
                  $this->redirect(array('action' => 'admin'));
                  $this->Session->setFlash('User Data Updated.');
               }
               else
               {
                  $this->Session->setFlash('There was a problem while Updating User.');
               }                    
            }
        }
    }
    else
    {
        $this->redirect(array('action' => 'login'));
        exit();
    }        
}

这是我的模特

<?php
class User extends AppModel
{
    var $name = 'User';
    var $validate = array(
        'username'=>array(
                  /* 'alphaNumeric'=>array(
                'rule'=>'alphaNumeric',
                'required'=>true,
                'message'=>'Alphabets and numbers only'
                ), */
            'between'=>array(
                'rule'=>array('between', 5, 15),
                'message'=>'Between 5 and 15 characters'
            )
        ),
        'password'=>array(
            'rule'=>array('minLength', 8),
            'required'=>true,
            'message'=>'Minimum 8 characters long'
        ),
        'email'=>'email'
    );
}

?>

1 个答案:

答案 0 :(得分:1)

创建或更新由模型的id字段控制。如果设置了$ Model-&gt; id,则更新具有此主键的记录。否则,将创建新记录。您可能需要检查$ this-&gt;数据是否包含:$ this-&gt; data ['User'] ['id']。如果没有,那就是创建新记录的原因。要解决此问题,您可以执行以下操作:

$this->data['User']['id'] = $this->Session->read('user_id');

当然,如果您将其存储在会话中。否则,您可能需要更新视图中的表单以保存用户ID的隐藏字段。但这并不像会话存储变量那样安全,具体取决于隐藏用户ID的安全需求。

快乐的编码!