更新记录,但使用记录ID以外的其他方式读取记录

时间:2011-08-10 16:38:22

标签: cakephp

我需要更新模型,但是使用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 个答案:

答案 0 :(得分:1)

您几乎必须知道要更新的记录的ID,如果您不知道它(即它不在URL,POST数据或会话中),找到它的唯一方法是执行查询(在您的情况下,在student_id上)。

我能想到的唯一建议是:

  • 不要忘记您可以通过设置Model::id(假设id中还没有$this->data键)指向记录
  • 如果您只保存单个字段,则可以使用Model::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'));             
    }