简体   繁体   中英

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

I am tryin to run the following action:

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

When i run this i get the following error:

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

How come?

You're in the EmployeesController then the save on the User model is not working because either

1.) You don't declare the User model as one of the model that the EmployeesController uses

class EmployeesController extends AppController {

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

or

2.) Your models don't have the correct relationship. If Employee belongsTo User or vice versa you can do

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

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

This line in your code showing that there should already be a relation between Employee and User model. In EmployeesController to save User you can try:

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

But if your relation not properly defined in models then you can do in EmployeesController like below:

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

and I hope your problem will be resolved.

I think you don't load model into your controller page. If you not then do this.

You just put your code in controller.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM