动态下拉和保存 cakephp 代码不能一起工作

Dynamic dropdown and save cakephp code not working together

我有三个表 'Categories' 、 'Courses' 和 'Subjects' 具有以下关联

  1. 类别有许多课程
  2. 课程属于类别,课程有多个主题
  3. Subject BelongsTo Course, Subject hasMany Notes
  4. 笔记属于主题

当我尝试保存数据时出现错误 'Call to a member function create() on null'.

class SubjectsController extends AppController {

    public $uses = array('Category','Course');

    public function add(){
        pr($this->request->data);die;
        if ($this->request->is('post')) {
            pr($this->request->data);die;
            $this->Subject->create();
            if ($this->Subject->save($this->request->data)) {
                $this->Flash->success(__('The subject has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Flash->error(__('The subject could not be saved. Please, try again.'));
            }
        }
    }
}

与你的Ajax无关。它在错误消息中告诉你正确的。您正在尝试从 null 对象调用 create 函数。在这种情况下,$this->Subject.

您有 $this->uses 类别和课程模型,但没有主题。您可以将其添加到此控制器使用的列表中,或者您可以通过与您已经使用的东西的现有关联来访问它:$this->Course->Subject.

确保检索到的数据正确,然后这样做:

$this->Subject->create();
$this->Subject->set(array($this->request->data);
$this->Subject->save();