在向数据库中添加新书时,我想要在新实体中修补请求并保存该实体。将请求修补到新实体的操作会将此实体返回给另一个方法。
代码是这样的:
public function bookAdder($book = [])
{
if ($this->Books->save($book)) {
$this->Flash->success(__('The book has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The book could not be saved. Please, try again.'));
return $this->redirect(['action' => 'add']);
}
}
public function add()
{
$user_id = $this->request->session()->read('Auth.User.id');
$book = $this->Books->newEntity();
if ($this->request->is('post')) {
$book = $this->Books->patchEntity($book, $this->request->data);
$book->set(array('user_id' => "$user_id"));
return $this->redirect(['action' => 'bookAdder', $book]);
}
$users = $this->Books->Users->find('list', ['limit' => 200]);
$this->set(compact('book', 'users'));
$this->set('_serialize', ['book']);
}
保存测试记录时,我收到此错误:
错误:路线匹配" / books / book-adder / {" title":" cc"," writer": " cc"," edition":" cc"," course":" cc"," description& #34;:" cc","价格": 2," user_id":" 1"}"无法找到。
我也试过public function bookAdder($book){ }
但仍然没有成功。
有什么方法可以解决这个问题吗?提前谢谢!
答案 0 :(得分:1)
多种功能!
您是否正在进行多种功能的练习?那' S 如果你让你的功能可重用且更具可读性,那就太好了。
但你在这里做的是增加一些复杂性。当您重定向到bookAdder函数时,您将生成如下所示的URL:
book-adder/%7B%0A%20%20%20%20"name"%3A%20"abc"%2C%0A%20%20%20%20"user_id"%3A%20"1"%0A%7D
您将实体作为函数参数传递。显然发生了路由错误。
所以至少对于你正在做的事情,你真的不需要多功能。
简单说明:
public function add()
{
$user_id = $this->request->session()->read('Auth.User.id');
$book = $this->Books->newEntity();
if ($this->request->is('post')) {
$book = $this->Books->patchEntity($book, $this->request->data);
$book->set(array('user_id' => "$user_id"));
if ($this->Books->save($book)) {
$this->Flash->success(__('The book has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The book could not be saved. Please, try again.'));
return $this->redirect(['action' => 'add']);
}
}
$users = $this->Books->Users->find('list', ['limit' => 200]);
$this->set(compact('book', 'users'));
$this->set('_serialize', ['book']);
}
如果你真的需要来自另一个功能程序的实体,那么流程应该是这样的:
makeEntity功能:
public function makeEntity($book = null,$requestData = []) {
$book = $this->Books->patchEntity($book, $requestData);
return $book;
}
添加功能:
public function add()
{
$user_id = $this->request->session()->read('Auth.User.id');
$book = $this->Books->newEntity();
if ($this->request->is('post')) {
$book = $this->makeEntity($book, $this->request->data);
$book->set(array('user_id' => "$user_id"));
return $this->redirect(['action' => 'bookAdder', $book]);
}
$users = $this->Books->Users->find('list', ['limit' => 200]);
$this->set(compact('book', 'users'));
$this->set('_serialize', ['book']);
}
并没有太大的区别。