我正在按照书籍教程更新当前数据
从书中
use Cake\ORM\TableRegistry;
$articlesTable = TableRegistry::get('Articles');
$article = $articlesTable->get(12); // Return article with id 12
$article->title = 'CakePHP is THE best PHP framework!';
$articlesTable->save($article);
这更新了ID 12上的文章标题。但是,如果我必须更新6 7个字段,该怎么办?就像我想做的那样。
这是我的代码,除非我单独提及每个字段,否则不会更新。
public function updateUser($user_data,$id){
$user = $this->get($id);
$user->first_name = $user_data['first_name'];
$user->last_name = $user_data['last_name'];
$this->save($user);
}
我的$user_data
数组的密钥与我想要更新的表格列完全相同。
答案 0 :(得分:0)
使用补丁实体,应该看起来像这样:
public function updateUser($user_data,$id){
$user = $this->get($id);
$user = $this->Users->patchEntity($user,$user_data);
$this->save($user);
}
了解更多信息:https://book.cakephp.org/3.0/en/orm/saving-data.html#validation-and-patchentity
您的控制器可以从updateUser.ctp调用,因此请尝试将其用作所有更新操作的标准:
public function edit($id)
{
$user = $this->Users->get($id);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user,$user_data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The {0} has been saved.', 'User '));
return $this->redirect(['action' => 'edit']);
} else {
$this->Flash->error(__('The {0} could not be saved. Please, try again.', 'User'));
}
}
$this->set(compact('user'));
}
您可以使用Cake Bake获取标准蛋糕方法:https://book.cakephp.org/3.0/en/bake/usage.html