CakePHP致命错误:在非对象(Controller)上调用成员函数create()

Cro*_*O'M 1 php controller cakephp

我有CakePHP控制器代码,它抛出以下错误'致命错误:在非对象上调用成员函数create()'.

控制器代码如下:

if ($this->request->is('post')) {
            $this->MonthlyReturn->create();
            $this->MonthlyReturn->saveField('company_id', $cid);    // Assign current company ID to this monthly return before saving
            if ($this->MonthlyReturn->save($this->request->data)) {
                $this->Session->setFlash(__('The monthly return has been saved'));
                $this->redirect(array('action' => 'index'));
            } else 
            {
                $this->Session->setFlash(__('The monthly return could not be saved. Please, try again.'));
            }
        }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

ori*_*ori 10

如果$uses在控制器内部定义,则需要显式加载MonthlyReturn模型:

var $uses = array('MonthlyReturn','Employee','Company');
Run Code Online (Sandbox Code Playgroud)

文档

  • 但是,如果员工和公司与MonthlyReturn相关,则有一个更好的方式来访问它们(没有定义`$ uses`).如果它们是相关的,你可以通过`$ this-> MonthlyReturn-> Employee`和`$ this-> MonthlyReturn-> Company`访问这些模型,这更像是CakePHP的做事方式.我相信(有人请纠正我,如果我错了)当你通过`$ uses`将Employee and Company加载到控制器中时,所有相关的模型也将加载到这些模型中(虽然它们已经在MontlyReturn中可​​用)增加内存负荷. (4认同)