Updating a record, but obtaining it reading with other than the records ID
I need to update a model, but look for the model using the student_id instead of the id of the model itself.
I came up with this solution but was wondering if there is a better way of doing it?
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' 开发者_JAVA技巧=> 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'));
}
You pretty much have to know the ID of the record you are updating, and if you don't know it (ie. it's not in the URL, POST data or session), the only way to find it is to perform a query (in your case, on the student_id
).
The only suggestions I can think of are:
- Don't forget you can point at a record by setting
Model::id
(assuming you don't already have anid
key in$this->data
) - If you are only saving a single field, you can use
Model::saveField()
.
Code:
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'));
}
精彩评论