【问题标题】:CakePHP Fatal error: Call to a member function create() on a non-object (Controller)CakePHP 致命错误:调用非对象(控制器)上的成员函数 create()
【发布时间】:2012-02-18 20:40:14
【问题描述】:

我有 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.'));
            }
        }

任何帮助将不胜感激。

【问题讨论】:

  • 你能告诉我们你的控制器的第一行吗?
  • ` App::uses('AppController', 'Controller'); /** * MonthlyReturns Controller * * @property MonthlyReturn $MonthlyReturn */ class MonthlyReturnsController extends AppController { var $uses = array('Employee','Company');`

标签: cakephp controller php


【解决方案1】:

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

var $uses = array('MonthlyReturn','Employee','Company');

documentation

【讨论】:

  • 不敢相信我错过了...谢谢,您为我省去了很多麻烦!
  • 稍微评论一下,如果 Employee 和 Company 与 MonthlyReturn 相关,则有更好的方法来访问它们(无需定义 $uses)。如果相关,可以通过$this->MonthlyReturn->Employee$this->MonthlyReturn->Company访问这些模型,这更像是CakePHP的做事方式。我相信(如果我错了,请有人纠正我)当您通过 $uses 将 Employee 和 Company 加载到控制器中时,所有相关模型也将加载到这些模型中(虽然它们已经在 MontlyReturn 中可用)增加内存负载。
【解决方案2】:

你应该像这样首先加载模型

$this->loadModel("MonthlyReturn");

这里的 MonthlyReturn 是模型的名称。

【讨论】:

    猜你喜欢
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    相关资源
    最近更新 更多