CakePHP - CRUD API:插入数据库 CakePHP 时出错
CakePHP - CRUD API: Error upon inserting to database CakePHP
我在尝试 POST 到 API 时收到以下错误。我已经按照本书的 this 教程进行操作,所以我不确定为什么插入不起作用。
Message: Call to member function error() on boolean
Trace: ControllerTrait.php
我的添加函数是通过bake创建的,但是尽管如此,这个错误似乎是在保存实体的过程中发生的。
public function add()
{
$author = $this->Authors->newEntity();
if ($this->request->is('post')) {
$author = $this->Authors->patchEntity($author, $this->request->data);
if ($this->Authors->save($author)) {
$this->Flash->success(__('The author has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The author could not be saved. Please, try again.'));
}
}
$this->set(compact('author'));
$this->set('_serialize', ['author']);
}
您不需要 add
操作,只需删除它 -- 这正是 CRUD 插件为您所做的。
如果你需要自定义一个CRUD操作你需要在最后return $this->Crud->execute()
,例如:
public function add()
{
$this->Crud->on('beforeSave', function (Event $e) {
// Custom logic before save
});
// Make sure CRUD takes care of the rest
return $this->Crud->execute();
}
但是,是的,如果您只是一起删除 add
方法,它将起作用。
我在尝试 POST 到 API 时收到以下错误。我已经按照本书的 this 教程进行操作,所以我不确定为什么插入不起作用。
Message: Call to member function error() on boolean
Trace: ControllerTrait.php
我的添加函数是通过bake创建的,但是尽管如此,这个错误似乎是在保存实体的过程中发生的。
public function add()
{
$author = $this->Authors->newEntity();
if ($this->request->is('post')) {
$author = $this->Authors->patchEntity($author, $this->request->data);
if ($this->Authors->save($author)) {
$this->Flash->success(__('The author has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The author could not be saved. Please, try again.'));
}
}
$this->set(compact('author'));
$this->set('_serialize', ['author']);
}
您不需要 add
操作,只需删除它 -- 这正是 CRUD 插件为您所做的。
如果你需要自定义一个CRUD操作你需要在最后return $this->Crud->execute()
,例如:
public function add()
{
$this->Crud->on('beforeSave', function (Event $e) {
// Custom logic before save
});
// Make sure CRUD takes care of the rest
return $this->Crud->execute();
}
但是,是的,如果您只是一起删除 add
方法,它将起作用。