CakePHP错误:对非对象调用成员函数save()
我正在尝试运行以下操作:CakePHP错误:对非对象调用成员函数save(),php,cakephp,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 th
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
为什么?您在EmployeesController中,那么用户模型上的保存不起作用,因为 1.)您不会将用户模型声明为EmployeesController使用的模型之一
class EmployeesController extends AppController {
var $uses = array('Employee', 'User');
或
2.)您的模型没有正确的关系。如果员工属于用户,反之亦然,您可以这样做
$user = $this->Employee->User->save($this->request->data);
如果您在EmployeesController中,则用户模型上的保存不起作用,因为 1.)您不会将用户模型声明为EmployeesController使用的模型之一
class EmployeesController extends AppController {
var $uses = array('Employee', 'User');
或
2.)您的模型没有正确的关系。如果员工属于用户,反之亦然,您可以这样做
$user = $this->Employee->User->save($this->request->data);
我认为您并没有将模型加载到控制器页面中。如果你没有那么做 您只需将代码放入控制器
public $uses = array('Employee', 'User');
我认为您并没有将模型加载到控制器页面中。如果你没有那么做 您只需将代码放入控制器
public $uses = array('Employee', 'User');
$this->request->data['Employee']['user\u id']=$this->user->id代码>
代码中的这一行表示员工
和用户
模型之间应该已经存在关系。在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);
我希望你的问题能得到解决。$this->request->data['Employee']['user\u id']=$this->user->id代码>
代码中的这一行表示员工
和用户
模型之间应该已经存在关系。在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);
我希望你的问题能得到解决。调用save()
时$this->User
中存储了什么?调用save()
时$this->User
中存储了什么?是的,这就是问题所在,但我不建议将User
粘贴在$uses
中。尝试使用$this->loadModel('User')
或ClassRegistry::init('User')
加载模型,以避免不必要地使用递归(如果员工与用户没有直接关系,就是这样)。是的,这就是问题所在,但我不建议在$uses
中粘贴User
。尝试使用$this->loadModel('User')
或ClassRegistry::init('User')
加载模型,以避免不必要地使用递归(如果员工与用户没有直接关系,就是这样)。