在编辑插入新行而不是更新 cakephp 2x 中的当前行

on editing inserting a new row instead of updating the current row in cakephp 2x

我在更新学生个人资料表格时遇到问题,在我将 user_id 给了学生 profile.Every 之后,当我尝试编辑表格时,在保存它时为现有用户。我不知道我哪里错了。请提前 help.Thanks。 这是我在学生资料控制器中的添加和编辑功能:

 public function add() {
   if ($this->request->is('post')) {
      $this->StudentProfile->create();
    $data = $this->request->data;
     $data['StudentProfile']['user_id'] = $this->Auth->user('id');
     // code implemented below               
     //$this->loadModel('User');

      if ($this->StudentProfile->save($data)) {
        //Update user here if Profile saved successfully 
        //$this->StudentProfile->id = $this->Auth->user('id');

            $this->Session->setFlash(__('Your account profile has been   created'));
            $this->redirect(array('controller' => 'studentprofiles',   'action' => 'index'));
        }else{
             $this->Session->setFlash(__('Your Profile was saved, but an  error has occurred while updating the Users table'));
            //Email your self the user ID here or something ??
        }
    } 
     $h=array(

  'fields' => array('Height.height'),
  'recrusive' => 0
);

    $this->loadModel('Height');
    $height = $this->Height->find('list',$h);
    $this->set(compact('height'));
}

public function edit($id = null) {
      if (!$this->StudentProfile->exists($id)) {
        throw new NotFoundException(__('Invalid student profile'));
      }
     if ($this->request->is(array('post', 'put'))) {
        $this->request->data['StudentProfile']['user_id'] = $this->Auth- >user('id');
      // code implemented below               
     // $this->loadModel('User');
        if ($this->StudentProfile->save($this->request->data)) {
            //$this->StudentProfile->id = $this->Auth->user('id');
            $this->Session->setFlash(__('The student profile has been   saved.'), 'default', array('class' => 'alert alert-success'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The student profile could not be   saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
        }
    } else {
        $options = array('conditions' => array('StudentProfile.' . $this-  >StudentProfile->primaryKey => $id));
        $this->request->data = $this->StudentProfile->find('first',   $options);
    }
      $h=array(

  'fields' => array('Height.height'),
  'recrusive' => 0
);

    $this->loadModel('Height');
    $height = $this->Height->find('list',$h);
    $this->set(compact('height'));
 }

不敢相信我正在回答我自己的问题。好吧如果有人有同样的上述问题,解决方案就是在这之后添加以下代码-

 $this->request->data['StudentProfile']['user_id'] = $this->Auth->user('id');
 // add this code to avoiding giving new id to existing user on edit:
        $this->request->data['StudentProfile']['id'] = $id;

保存编辑信息的更好方法是在保存前在模型上设置ID,如下所示

$this->StudentProfile->id = $this->Auth->user('id');

如果您在上述设置后启动保存,那么该行将被编辑,而不是添加新行。