【问题标题】:can't update an existing record in CakePHP无法更新 CakePHP 中的现有记录
【发布时间】:2013-03-17 08:15:09
【问题描述】:

我写了一个编辑函数来更新用户的信息,我的代码:

if($this->request->is('post')){
                $this->request->data['User']['password']=Security::hash($this->request->data['User']['password'],'sha1', Configure::read('Security.salt'));
                $this->request->data['User']['type'] = '2';
                $this->request->data['User']['username'] = $username;
                //debug($this->request->data);
                if($this->User->validates()){
                    $this->User->set($this->request->data['User']);
                    if ($this->User->save($this->request->data,false)) {
                        $this->Session->setFlash(__('The user has been saved'));
                        $this->redirect($this->root.'index');
                    } else {
                        $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                    }
                }
            }

但我检查了这个函数:$this->User->exists() 从不返回 true,在我的情况下,用户表键是用户名,当我编辑用户名时,这个函数可以将新信息保存为新记录,但是当我没有编辑用户名,无法保存新信息,为什么会这样以及如何更正我的功能来编辑记录?

【问题讨论】:

  • 所以表的主键是用户名,你想更新那个键吗?为什么不添加一个id 字段让您的生活更轻松。
  • 我想更新这条记录的所有字段,但是这段代码只能创建新记录

标签: cakephp sql-update cakephp-2.0 cakephp-model editmodel


【解决方案1】:

相信我,您几乎总是希望在您的表中拥有id。添加它并使其成为主键。

现在看起来像这样:

if($this->request->is('post')){

    // Think about using AuthComponent:
    // $this->request->data['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
    $this->request->data['User']['password'] = Security::hash($this->request->data['User']['password'],'sha1', Configure::read('Security.salt'));
    $this->request->data['User']['type'] = '2';
    $this->request->data['User']['username'] = $username;
    $this->User->id = $id;

    // Checking if the user exists.
    if(!$this->User->exists()){
        // If not, tell it here.
    }

    if($this->User->validates()){
        if ($this->User->save($this->request->data, false)) {
            $this->Session->setFlash(__('The user has been saved'));
            $this->redirect($this->root.'index');
        } else {
            $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
        }
    }else{
        // Something went wrong.
    }
}

如果你的主键有用户名,每次不同时,CakePHP 都会创建一个新记录。

现在,我会给你我的函数read 与 AJAX 调用,也许它会帮助你。

// Function for creating and updating users.
    public function update(){

        // If the request is AJAX (from Ext-JS).
        if($this->request->is('ajax')){

            // Prepare data for CakePHP. $this->request->data['ModelName'] => array of data.
            $this->request->data['User'] = $this->request->data;

            // If there is "id" in data, then it's "edit".
            // If there is no "id" in data, then it's "add".
            if($this->request->data['id'] != null){

                // Setting "id" for user so the CakePHP could use "save", "saveAll", "exits" or 
                // any other function for a particular user.
                $this->User->id = $this->request->data['id'];

                // Checking if the user exists.
                if (!$this->User->exists()) {

                    // If there is no user with a given "id", remove the data (security reasons).
                    // Put the "success" and "message" (message) properties.
                    $this->request->data = array();
                    $this->request->data['success'] = false;
                    $this->request->data['message'] = "No user with this id.";

                    // Return the message to Ext-JS.
                    return new CakeResponse(array('body' => json_encode($this->request->data)));
                }

                // List of fields to save.
                $fieldList = array('id', 'first_name', 'last_name', 'username', 'role_id', 'language_id', 'status', 'last_login', 'created', 'modified');

                // Only if there is an password provided by user, save it.
                if($this->request->data['User']['password'] != ''){
                    array_push($fieldList, 'password');
                }

                // If you are here, then there is a user with a given "id" and you are editing that user.
                if ($this->User->save($this->request->data, true, $fieldList)) {

                    // Remove any data except the "success" and "message" (message) properties (security reasons).
                    $this->request->data = array();
                    $this->request->data['success'] = true;
                    $this->request->data['message'] = "The user has been changed.";
                }else {

                    // If you are here, something went wrong with editing a user. Remove the data (security reasons).
                    // Put the "success" and "message" (message) properties.
                    $this->request->data = array();
                    $this->request->data['success'] = false;
                    $this->request->data['message'] = "Error with editing.";
                }
            }else{

                // If you are here, then you are adding a new user (because there is no "id" in data). Create a new row in table.
                $this->User->create();

                // Try to save the user with data from $this->request->data['User'].
                if ($this->User->save($this->request->data)) {

                    // If you are here, then everything is ok. Remove any data and tell that to Ext-JS with "success" and "message" (message) properties.
                    $this->request->data = array();
                    $this->request->data['success'] = true;
                    $this->request->data['message'] = "The user has been added.";
                }else{

                    // If you are here, something probably went wrong with $this->request->data['User'].
                    // Remove any data (security reasons) and tell that to Ext-JS with "success" and "message" (message) properties.
                    $this->request->data = array();
                    $this->request->data['success'] = false;
                    $this->request->data['message'] = "Something went wrong with adding a user.";
                }
            }

            // Return any data to Ext-JS, despite the success.
            // $this->request->data['success'] => (true | false).
            // $this->request->data['message'] => (message for Ext-JS).
            return new CakeResponse(array('body' => json_encode($this->request->data)));
        }
    }

现在,您将 Session 消息发送给用户,而不是 return new CakeResponse

【讨论】:

  • $user_info里面有数据吗?将debug($user_info) 放在if($this->request->is('post')){ 部分上方。换桌后你编辑Model了吗?
【解决方案2】:

调试您的代码

if($this->User->validates()){

在此之前,问题中的代码中没有完成以下任何操作:

  • 致电create
  • 在模型上调用set

因此,这里发生的是代码尝试验证一个空模型对象。假设返回 false(正如问题所暗示的那样),保存“不起作用”的原因是代码没有调用 save

但我检查了这个函数:$this->User->exists() never return true

正常,因为没有调用 createset 或设置 User->id 属性。

参考文档

显式调用validates 很好,但也没有必要。 Save 已经调用验证 - 因此,如果您的代码有效,您将运行两次验证规则。

使用来自the book的这个例子作为参考:

public function edit($id) {
    if ($this->request->is('post')) {
        if ($this->Recipe->save($this->request->data)) {
            $this->Session->setFlash('Recipe Saved!');
            $this->redirect('/recipes');
        }
    }

    $this->set('recipe', $this->Recipe->findById($id));
}

【讨论】:

    【解决方案3】:

    尝试以下步骤

    if ($this->User->save($this->request->data,false)) {

            $this->Session->setFlash(__('Recipe Saved!'));
    
            return $this->redirect(array('action' => 'view_users'));
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多