CakePHP错误:在非对象上调用成员函数save()

时间:2013-08-09 13:15:33

标签: php cakephp

我正在尝试运行以下操作:

public function add() {
if (!empty($this->request->data)) {
    // We can save the User data:
    // it should be in $this->request->data['User']

    $user = $this->User->save($this->request->data);

    // If the user was saved, Now we add this information to the data
    // and save the Profile.

    if (!empty($user)) {
        // The ID of the newly created user has been set
        // as $this->User->id.
        $this->request->data['Employee']['user_id'] = $this->User->id;

        // Because our User hasOne Profile, we can access
        // the Profile model through the User model:
        $this->Employee->save($this->request->data);
    }
}

当我运行时,我收到以下错误:

Error: Call to a member function save() on a non-object
File: /var/www/bloglic-2013/cake/app/Controller/EmployeesController.php
Line: 61

怎么回事?

3 个答案:

答案 0 :(得分:3)

您在EmployeesController中,然后用户模型上的保存无效,因为

1。)您没有将User模型声明为EmployeesController使用的模型之一

class EmployeesController extends AppController {

    var $uses = array('Employee', 'User'); 

2。)您的模型没有正确的关系。如果员工属于用户,反之亦然

$user = $this->Employee->User->save($this->request->data);

答案 1 :(得分:3)

$this->request->data['Employee']['user_id'] = $this->User->id;

代码中的这一行显示EmployeeUser模型之间应该存在关联。在EmployeesController保存User,您可以尝试:

$this->Employee->User->create();
$this->Employee->User->save($this->request->data);

但如果你的关系没有在模型中正确定义,那么你可以在EmployeesController中进行如下操作:

$this->loadModel('User');
$this->User->create();
$this->User->save($this->request->data);

我希望你的问题能得到解决。

答案 2 :(得分:0)

我认为您不会将模型加载到控制器页面中。如果你不这样做的话。

您只需将代码放入控制器即可。

public $uses = array('Employee', 'User');