1

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

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

怎么来的?

4

3 回答 3

3

您在 EmployeesController 中,然后保存在 User 模型上不起作用,因为要么

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

class EmployeesController extends AppController {

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

或者

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

$user = $this->Employee->User->save($this->request->data);
于 2013-08-09T13:18:26.270 回答
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);

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

于 2013-08-09T15:55:31.003 回答
0

我认为您不会将模型加载到控制器页面中。如果您不这样做,请执行此操作。

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

public $uses = array('Employee', 'User'); 
于 2013-08-09T13:26:33.007 回答