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


CakePHP Error: Call to a member function save() on a non-object

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

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

为什么?

$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);

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

如果您在EmployeesController中,则用户模型上的保存不起作用,因为

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

class EmployeesController extends AppController {
    var $uses = array('Employee', 'User'); 

2.)你的模特没有正确的关系。如果员工属于用户,反之亦然,您可以进行

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

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

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

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