我正在用cakePHP编写一个网站。我在VideosControllers中写了一个“add”函数:
public function admin_add(){
$this->Video->create();
$this->Video->save(array(
'name' => 'New video'
));
return $this->redirect(array(
'controller' => 'Videos',
'action' => 'admin_edit',
$this->Video->id
), 301);
}
此功能没有视图。
当我调用此函数admin_add时,我被重定向到admin_edit页面,但该函数不会在数据库和admin_edit中创建任何视频。
我试图在返回之前放置一个die(),但无论如何都会重定向用户,这很奇怪。
答案 0 :(得分:2)
save()编码不正确。你需要这个:
$this->Video->save(array($this->Video->alias => array('name' => 'New Video')));
或者您可以对别名进行硬编码:
$this->Video->save(array('Video' => array('name' => 'New Video')));
修改强>
我的回答与the CakePHP 2.x book相符。但是,我错了。该书中没有提到的变体允许将模型名称省略为数组键。如果您有兴趣,请在您的Cake核心文件版本中关注Model::save()
到Model::set()
。
我查看了CakePHP 2.6的核心文件,发现它能够在第一个save()参数的基础上做很多事情。这些变体由单元测试覆盖,因此它们可能仍可在CakePHP 2.x中使用。