我在cakephp工作并且有Lessons
Belongsto Kid
关系和Kid hasMany Lessons
关系。该文件位于LessonsController中。我想按照课程查找与本课程相关的孩子,并更改与paid_lessons
相关联的Kid
变量。虽然我们已加载模型,但此行$this->Lesson->Kid->set('paid_lessons','5');
由于某种原因不起作用。有什么建议吗?
public function lessoncompleted($id = null) {
$this->loadModel('Kid');
if (!$this->Lesson->exists($id)) {
throw new NotFoundException(__('Invalid task'));
}
$this->Lesson->id = $id;
$this->Lesson->set('completed', 'yes');
$this->Lesson->Kid->set('paid_lessons','5');
if ($this->Lesson->save($this->request->data)) {
$this->Session->setFlash(__('The task has been updated.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The task could not be saved. Please, try again.'));
}
}
答案 0 :(得分:0)
因为$ this-> Lesson-> save($ this-> request-> data)会在保存过程中调用$ this-> set($ data),不会覆盖$ this-&gt ;课程 - >设置('已完成','是'); ?
答案 1 :(得分:0)
您没有使用set correctly实际上,您不需要它,因为您在控制器中执行此操作并假设您要为模型保存数据Lesson和Kid我会这样做
//Assuming that Lesson hasMany Kid
public function lessoncompleted($id = null) {
//$this->loadModel('Kid'); No need to load Kid because it is already loaded by Lesson
if (!$this->Lesson->exists($id)) {
throw new NotFoundException(__('Invalid task'));
}
//$this->Lesson->id = $id; //not necessary because $this->request->data['Lesson']['id'] should contain the ID
//$this->Lesson->set('completed', 'yes'); //no, see the next line
$this->request->data['Lesson']['completed'] = 'yes';
//$this->Lesson->Kid->set('paid_lessons','5'); //No, see next line
$this->request->data['Lesson']['Kid'][0]['paid_lessons'] = 5;
//if ($this->Lesson->save($this->request->data)) { //use saveAssociated
if ($this->Lesson->saveAssociated($this->request->data)) {
$this->Session->setFlash(__('The task has been updated.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The task could not be saved. Please, try again.'));
}
}
如果此代码不起作用,我需要检查$ this-> request->数据的内容,如果需要,请将其粘贴到此处,我也很高兴阅读您所拥有的关联课程和孩子模型