2011-08-10 13 views
0

モデルを更新する必要がありますが、モデル自体のidの代わりにstudent_idを使用してモデルを探します。レコードを更新していますが、レコードID以外の値を取得していますID

私はこの解決策を考え出しましたが、それを実行するより良い方法があるのだろうかと疑問に思っていましたか?あなたは(すなわち。それはURL、POSTデータまたはセッションではありません)それを知らない場合はかなりあなたが更新されたレコードのIDを知っている必要があり、かつ

if (!empty($this->data)) { 

// function that calculates score from answers in $this->data 
     $score = $this->OnlineExam->checkAnswers(2,$this->data);  

     // find the record 
     $record = $this->OnlineExam->find('first', array(
           'conditions' => array('OnlineExam.student_id' => $this->Session->read('OnlineExam.studentId')), 
           'fields' => array('OnlineExam.id'))); 
     // set the id and the score in the data array 
     $this->data['OnlineExam']['id'] = $record['OnlineExam']['id']; 
     $this->data['OnlineExam']['scoreB'] = $score; 

     // save the model 
     if($this->OnlineExam->save($this->data)) { 
      $this->redirect(array('controller' => 'OnlineExams', 'action' => 'page3'));    
     } 

答えて

1

、見つけるための唯一の方法(あなたの場合はstudent_idで)クエリを実行することです。私は考えることができる

唯一の提案は以下のとおりです。

  • 場合は(すでに$this->dataidキーを持っていないと仮定して)あなたはModel::idを設定することで、レコードを指すことができます忘れないでください1つのフィールドだけを保存している場合は、Model::saveField()を使用できます。

コード:より良いsaveFieldチップ用

if (!empty($this->data)) { 
    // function that calculates score from answers in $this->data 
    $score = $this->OnlineExam->checkAnswers(2, $this->data); 
    // find the record 
    $record = $this->OnlineExam->find('first', array(
     'conditions' => array('OnlineExam.student_id' => $this->Session->read('OnlineExam.studentId')), 
     'fields' => array('OnlineExam.id') 
    )); 
    // set the id and save the score 
    $this->OnlineExam->id = $record['OnlineExam']['id']; 
    $saved = $this->OnlineExam->saveField('scoreB', $score); 
    if ($saved) { 
     $this->redirect(array('controller' => 'OnlineExams', 'action' => 'page3'));    
    } 
+0

感謝.. – AlexBrand

関連する問題