我需要更新模型,但是使用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'));
}
答案 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'));
}