2011-08-10 4 views
0

모델을 업데이트해야하지만 모델 자체의 ID 대신 student_id를 사용하여 모델을 찾아야합니다.레코드를 업데이트하지만 레코드 이외의 값으로 읽음 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

당신은 당신이 업데이트중인 레코드의 ID를 알고 있고, 당신이 모르는 경우 (즉. 그것은 URL에없는, POST 데이터 또는 세션), 유일한 방법은 찾아 쿼리를 수행하는 것입니다 (귀하의 경우에는 student_id에서). 내가 생각할 수있는

유일한 제안은 다음과 같습니다

  • 하면 (이미 $this->dataid 키가없는 가정) 당신이 Model::id을 설정하여 기록을 가리킬 수 있습니다 잊지 마세요 단일 필드 만 저장하면 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

관련 문제