在 LAMP 设置(Ubuntu 13.10、Apache 2、MySQL Server 5.5、PHP 5.5.3)上使用 CakePHP 2.4.9。
试图将模型(用户)打包到插件中,但我遇到了一个奇怪的问题:
在两个不同的操作中,我使用 save()
创建或更新用户。这有效:
if ($this->request->data) {
if ($this->User->create() && $this->User->save($this->request->data)) {
$this->Session->setFlash(_('<strong>Congratulations!</strong> Successfully created a new user.'), 'default', array('class' => 'alert alert-success'));
$this->redirect(array('action' => 'register'));
} else {
$this->Session->setFlash(_('<strong>Oops!</strong> Could not create a new user.'), 'default', array('class' => 'alert alert-danger'));
}
}
但这行不通:
if ($this->request->data) {
$this->User->id = $id;
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(_('<strong>Congratulations!</strong> Successfully updated your user account.'), 'default', array('class' => 'alert alert-success'));
$this->redirect(array('action' => 'settings'));
} else {
$this->Session->setFlash(_('<strong>Oops!</strong> Could not update user account.'), 'default', array('class' => 'alert alert-danger'));
}
}
当我尝试保存后一个示例(“更新操作”)时,出现以下错误:
Fatal Error
Error: Call to a member function getColumnType() on a non-object File: /home/johan/sites/userplugin/lib/Cake/Model/Model.php Line: 1412
Notice: If you want to customize this error message, create app/View/Errors/fatal_error.ctp
表单非常标准,我使用 FormHelper
创建表单和字段。但是在更新表单中,我有一个带有 ID 的隐藏字段:
<?php echo $this->Form->hidden('id'); ?>
如果我删除它,更新表单会通过但会创建一个新对象!所以这就像 $this->User->id = $id
什么也没做。我目前“手动”设置了 $id
,所以 $id = 1
...
我尝试搜索类似的问题,但没有找到任何内容。一个讨论提到了 ID 字段,也许它没有正确设置?但我找不到任何解决方案。
最佳答案
模型引用错误
不同的代码排列并不直接与问题相关 - 或者可能只是表明另一个不同的问题=)。
line of code that is failing这是:
$this->{$model}->getColumnType($column);
其中 $this
是用户模型实例。 可能 的意思是,当它失败时,该对象不是您希望检查的类,只需执行以下操作:
debug(get_class($this->User));
在您的 Controller 中,它很可能是 AppModel
。
是什么原因造成的
这种“有时有效,有时无效”问题的典型原因是有一些使用插件前缀对模型的引用,而有些则没有,即
<?php
App::uses('MyPluginAppModel', 'MyPlugin.Model');
class Group extends MyPluginAppModel {
public $hasMany = array(
'User' => array(
'className' => 'User'
),
#'User' # Or like this
)
}
而它应该是这样的:
<?php
App::uses('MyPluginAppModel', 'MyPlugin.Model');
class Group extends MyPluginAppModel {
public $hasMany = array(
'User' => array(
'className' => 'MyPlugin.User'
),
#'MyPlugin.User' # Or like this
)
}
这里发生的事情取决于首次访问相关模型的方式,以及填充类注册表中的 User
键并为该模型引用的所有后续请求返回的内容。
要解决此问题,请确保始终使用正确的插件前缀引用模型(如果不是插件模型,则当然没有前缀)。
关于php - 无法使用 save() 在 CakePHP 中更新(但创建新的)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427817/