今回はcakePHPにおいてBooksというモデルがあったとします。 このBooksはそれぞれSummaryというあらすじを書くためのカラムを持っているとします。特定の本を洗濯したのち、この”Summary”というカラムのみpostDataからコントローラーで保存する時は、
public function editSummary($book_id){
$book = $this->Books->get($book_id);
$connection = ConnectionManager::get('default');
try{
if(empty($book)) throw newNotFoundException(__('Book Not Found'));
if($this->request->is(['post'])){
$postData = $this->request->getData(); // [ 'summary' => 'this book is super great!' ];
$this->Books->patchEntity($book, $postData, [
'fields' => 'summary',
]);
$this->Books->saveOrFail($book);
$connection->commit();
$this->Flash->success(__('Success to edit summary!'));
return $this->redirect('/edit');
}
} catch (\Throwable $e) {
$connection->rollback();
}
$this->set(compact($book));
return $this->render('/edit');
}
ポイントはpatchをする時に’fields’で追加するフィールドを指定すること。 公式には’fieldList’を使えって書いてあったのですが、テストを回した時にDeprecated Errorが出たので’fields’にしました。


